Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upload data from CSV to Django model
For this purpose we can write a script that would do the job. But I want a batch update on database using csv file. I tried django-adaptors also. Is there any other way to achieve this? -
celery beat fail when using djcelery schedule
I have a bit of a challenge and wonder if someone can help. I don't have any problem running celery manually,however if I use the beat with djcelery scheduler, I get a bunch of database errors. worker: Warm shutdown (MainProcess) (environment) [root@pse apps]# celery -A services_backend beat -l debug --max-interval=10 celery beat v3.1.26.post2 (Cipater) is starting. __ - ... __ - _ Configuration -> . broker -> redis://localhost:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> djcelery.schedulers.DatabaseScheduler . logfile -> [stderr]@%DEBUG . maxinterval -> 10.00 seconds (10.0s) [2020-03-24 01:46:42,962: DEBUG/MainProcess] Setting default socket timeout to 30 [2020-03-24 01:46:42,964: INFO/MainProcess] beat: Starting... [2020-03-24 01:46:42,964: DEBUG/MainProcess] DatabaseScheduler: intial read [2020-03-24 01:46:42,964: INFO/MainProcess] Writing entries (0)... [2020-03-24 01:46:42,964: CRITICAL/MainProcess] beat raised exception <class 'AttributeError'>: AttributeError("'DatabaseFeatures' object has no attribute 'autocommits_when_autocommit_is_off'",) Traceback (most recent call last): File "/opt/pse/apps/environment/lib/python3.6/site-packages/kombu/utils/_init__.py", line 323, in __get_ return obj.__dict__[self.__name__] KeyError: 'scheduler' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/pse/apps/environment/lib/python3.6/site-packages/celery/apps/beat.py", line 112, in start_scheduler beat.start() File "/opt/pse/apps/environment/lib/python3.6/site-packages/celery/beat.py", line 470, in start humanize_seconds(self.scheduler.max_interval)) File "/opt/pse/apps/environment/lib/python3.6/site-packages/kombu/utils/_init__.py", line 325, in __get_ value = obj.__dict__[self.__name__] = self.__get(obj) File "/opt/pse/apps/environment/lib/python3.6/site-packages/celery/beat.py", line 512, in scheduler return self.get_scheduler() File "/opt/pse/apps/environment/lib/python3.6/site-packages/celery/beat.py", line 507, in get_scheduler lazy=lazy) File "/opt/pse/apps/environment/lib/python3.6/site-packages/celery/utils/imports.py", line 53, in … -
How to deal with authorization with DRF and React
I'm building an app using Django as backend and React as frontend, for the user authentication I will use JWT Authentication. My doubt is when I need to get data from the API without the need to be an authenticated user, how I accomplish this? Using API keys?. I read that API keys are not mean for Authentication but authorization? This will be the case? -
Reverse accessor for 'FullNcr.manager' clashes with reverse accessor for 'FullNcr.user'
I have a form that when posted will assign the current user as the author of that form. I also want to assign a different user as the manager of the posted form but when referencing the user model as a foreign key for the manager it gives the error that it clashes with user. Any help would be great thanks models look like this: from django.db import models from django.contrib.auth.models import User class FullNcr(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) manager = models.ForeignKey(User, null=True, on_delete=models.CASCADE) -
Django-select2 Select2TagWidget on inlineformset
I'm quite lazy so I try to use Django pre-built features at the maximum. My models are : Room (eg bedroom), FurnitureReference (eg bed, lamp ...) RoomFurniture (piece of furniture[FurnitureRerence], quantity...) as a "through" (intermediate model) table I have managed to have an UpdateView with an inline formset that goes like this, each row has: a select to pick the furniture reference multiple inputs for quantity, location ... The inlineformset comes with extra = 5. Everything worked perfectly thus far. Now, if the furniture reference doesn't exist, the user has to add it elsewhere and then come back on this form. I wanted to allow him to create a furniture reference by simply typing a new reference. That's when I found Select2TagWidget. I managed to make it work on a simpler form by customizing the default value_from_datadict method to my needs. But with inlineformset, everything crashes. My issues are : When I submit the form every row is considered modified even the extras which I left empty. When I leave no extras, i get a form error message that says I would be very grateful if anyone could give me a hand on any of these 2 issues, or maybe … -
django.db.utils.IntegrityError: NOT NULL constraint failed: home_post.author_id
I have built a form for posting using Ajax, however, when I click on the submit button i get the error: django.db.utils.IntegrityError: NOT NULL constraint failed: home_post.author_id I do not know what this is as before I had a separate html for creating posts but after using Ajax I am getting this error. This is my Post Model: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(validators=[MaxLengthValidator(250)]) author = models.ForeignKey(Profile, on_delete=models.CASCADE) date_posted = models.DateTimeField(auto_now_add=True) last_edited= models.DateTimeField(auto_now=True) likes= models.ManyToManyField(Profile, blank=True, related_name='post_likes') This is my post form: class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','content',) This is my create_post view: @login_required def post_create(request): data = dict() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True posts = Post.objects.all() data['posts'] = render_to_string('home/homepage/home.html',{'posts':posts}) else: data['form_is_valid'] = False else: form = PostForm context = { 'form':form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) This is my Ajax Javascript code: $(document).ready(function(){ var ShowForm = function(){ var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType:'json', beforeSend: function(){ $('#modal-post').modal('show'); }, success: function(data){ $('#modal-post .modal-content').html(data.html_form); } }); }; var SaveForm = function(){ var form = $(this); $.ajax({ url: form.attr('data-url'), data: form.serialize(), type: form.attr('method'), dataType: 'json', success: function(data){ if(data.form_is_valid){ $('#post-list div').html(data.posts); $('#modal-post').modal('hide'); } else { … -
Django user profile only shows logged in user information
I am attempting to create a website where all user profiles are public. I have used AbstractUser for any changes to the base user model later on. I made the remainder of the user information in a UserProfile model. As of now, regardless of the profile I click on I am only seeing information for the currently logged-in user. This is my first time using class-based views and I think I'm veering off into the wrong direction. # users/models.py import uuid # for profile slugs from django.db import models from django.conf import settings from django.db.models.signals import post_save # signal for profile creation from django.contrib.auth.models import AbstractUser # import base user model for profile from django.dispatch import receiver from allauth.account.signals import user_signed_up class CustomUser(AbstractUser): pass class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) city = models.CharField(max_length=60, default="") ... profile_uuid = models.UUIDField( primary_key=False, default=uuid.uuid4, editable=False, unique=True ) # to use as a "slug" for profiles def __str__(self): return self.user.first_name @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) I'm trying to use the profile_uuid as my "slug" for the URL. It will come up as "https://example.com/profile/". # urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', … -
Trouble with model queries in Django
I have two models, as shown below: class Paper(Model): owner = ForeignKey(User, on_delete=CASCADE,) category = ForeignKey(Category, on_delete=CASCADE,) citation = TextField() paper = FileField(upload_to=user_directory_path) title = CharField(max_length=500) year = IntegerField() class Notes(Model): paper = ForeignKey(Paper, on_delete=CASCADE,) notes = TextField() owner = ForeignKey(User, on_delete=CASCADE) I'm trying and failing to form the appropriate Python code to return two different query sets: The first queryset should contain all Paper objects where a Notes object exists for the currently logged in user (i.e., a paper in this list means the user has submitted notes for the paper). The second queryset should contain all Paper objects where a Notes object does not exist for the currently logged in user (i.e., a paper in this list means that the user has not yet submitted their notes) Multiple users may submit notes for the same paper. My first attempts (with hard-coded values for testing): Paper.objects.exclude(notes__owner_id=3) # I would expect this to return Paper objects that don't have a Notes object for user with ID 3, but might have other notes objects associated with them Paper.objects.filter(notes__owner_id=3) # I thought this might return the opposite of the first but doesn't -
Django Menu and Sub_menu cannot display Sub menu properly
I am trying to displaying Menu and Sub Menu in table format like. Menu1 Menu2 SubMenu1 SubMenu2 SubMenu3 Menu3 SubMenu4 SubMenu5 SubMenu6 Menu4 but i'm getting wrong. menu1 submenu1 menu2 submenu2 and when I'm adding new submenu it's appearing under both main menu my models.py for menu app from django.db import models class Menu(models.Model): menu_name = models.CharField(max_length=100,blank=True) menu_slug = models.SlugField(max_length=100,unique=True,blank=True) menu_icon = models.ImageField(upload_to="imagemenu",blank=True) def __str__(self): return self.menu_name class Submenu(models.Model): submenu_name = models.CharField(max_length=100,blank=True) submenu_slug = models.SlugField(max_length=100, unique=True,blank=True) submenu_icon = models.ImageField(upload_to="imagemenu",blank=True) parent_menu = models.ManyToManyField(Menu, verbose_name=("Mtavari Menu")) def __str__(self): return self.submenu_name my views.py from django.shortcuts import render from django.http import HttpResponse from menu.models import Menu,Submenu # Create your views here. def HomePage(request): template = "front/Homepage.html" menu_item = Menu.objects.all() menu_submenu = Submenu.objects.all() return render(request,template, {"menu_item":menu_item,}) template file <ul> {% for menu in menu_item %} <li> <a href="#">{{menu.menu_name}}</a> <ul class="sub-menu"> {% for sub in menu_submenu %}<li><a href="index.html">{{sub.submenu_name}}</a></li>{% endfo %} </ul> </li> {% endfor %} </ul> -
get username of facebook account using django
I make a web application using django framework and I want to get username of facebook account who press or click a specific link like google or any link I will give it to him to know who is pressed the anchor link any idea that can help me please and thanks -
How to delete the parent object related through a many to many field?
I have three related models - Document, Collection, and CollectionDocument. A Collection object is made up of a group of documents. class Document(Model): document_id = models.AutoField(primary_key=True) class Collection(Model): collection_id = models.AutoField(primary_key=True) document = models.ManyToManyField(Document, through='CollectionDocument', related_name='collections',) class CollectionDocument(Model): collection_id = models.ForeignKey(Collection, on_delete=models.CASCADE, ) document = models.ForeignKey(Document, on_delete=models.CASCADE, ) In the Djangop Admin, I have a DocumentAdmin and a CollectionAdmin with the CollectionDocument as inlines in the CollectionAdmin. When I delete all the documents associated with a Collection, I also want the Collection to be deleted. Right now, when I delete the documents in a Collection, the CollectioDocument is empty, but the Collection still exists without any documents associated with it. I have tried several ways to do it using pre- and post-delete signals for the CollectionDocument model, but nothing seems to work. Have I structured my models incorrectly? How do I get the Collection to be deleted when all the associated Documents are deleted? Thanks! Mark -
How to include additional details in Django admin error reporting?
I'm using the process described in https://docs.djangoproject.com/en/3.0/howto/error-reporting/ to have my application send me error reports. I've noticed that these error reports are sent for both unhandled exceptions (for example a KeyError raised somewhere in my view, and not caught) as well as when my view returns a 500 Response intentionally. For example, one of my views handles an exception raised by a 3rd party library, and returns a 500 Response with some additional details about the exception like so: def post(self, request, pk): try: # something except (ExceptionFromSomeLibrary) as ex: return Response( data=ex.to_dict(), # I'd like this info to be included in the error report status=status.HTTP_500_INTERNAL_SERVER_ERROR ) #... When this exception occurs, the response returns as expected, and I receive an admin email. This email, however, doesn't contain a traceback (since the exception was handled) and does not include any of the information I sent back to the client (data=ex.to_dict()). It only shows me that a 500 Response was returned, and the route from which it originated: # example body of the email Internal Server Error: /api/releases/511/ Report at /api/releases/511/ Internal Server Error: /api/releases/511/ # below this are the request details and Django settings etc. Is there a way that … -
Can run server via "python manage.py runserver"
I want to run my virtual env. via "python manage.py runserver" but alway get this message "RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.abstractbaseuser'="">. Was __classcell__ propagated to type.__new__?" Does anyone know what causes this problem? I'm using Django 1.10 and Python 3.5.8 Thanks in advance, Chris -
Multiple Google Charts in Django Template in a loop or other suitable data vizualisation
I have a Django Template. The Template loops through elements as follows: {% for x in queryset %} code {% endfor %} and prints a table with numbers, eg. 10 rows x 4 columns. - For every row I want to take 4 numbers and bild a separate chart for every row, if possible after every row. But the Google chart appears on the same place and instead of 10 expected charts after every row, I get only one chart on the top of the page. - Is there a way to display one or more different charts for every row in a loop, using Google Charts? - Is Google Charts the proper solution for such a task? Which simple visualization package could be a solution. - Thank you. -
Django Object Not created after form submission
Hi I am using Django and Ajax for users create 'Posts' on their website. However, After the form submission the post is not shown. I do not know what's causing this as I see no errors. My views for the homepage and creating a post is: @login_required def home(request): posts = Post.objects.all() context = {'posts':posts} return render(request, 'home/homepage/home.html', context) @login_required def post_create(request): data = dict() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True posts = Post.objects.all() data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts}) else: data['form_is_valid'] = False else: form = PostForm context = { 'form':form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) my post_create.html: {% load crispy_forms_tags %} <form method="POST" data-url="{% url 'home:post-create' %}" class="post-create-form"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" >Create a Post</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{ form|crispy }} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Post</button> </div> </form> My home.html: {% extends "home/homepage/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block javascript %} <script src="{% static 'js/post.js' %}"></script> {% endblock javascript %} {% block content %} <div class="card"> <div class="card-body"> <div class="media mb-0 align-items-center"> <img class="img-create-post rounded-circle my-0 mr-3" style="width: 50px;height: 50px;" … -
Testing Keras Model using Django
I downloaded a Django API which I wanted to test with my Keras model, but whenever I tried to run the server it shows me this error, what's wrong? (base) C:\Users\vipek\PAS>python manage.py runserver Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\vipek\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\vipek\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "C:\Users\vipek\Anaconda3\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Users\vipek\Anaconda3\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Users\vipek\Anaconda3\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\vipek\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\vipek\PAS\api\settings.py", line 23, in <module> SECRET_KEY = os.environ['SECRET_KEY'] File "C:\Users\vipek\Anaconda3\lib\os.py", line 678, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' -
django channel deploy with nginx redis
I try to deploy Django app with a part based on Django channels on locall there is no problem and it works correctly but for deploying it on a server I have a problem ws routs are missing I tried to deploy as this and there are my files: nginx.conf upstream django { server 127.0.0.1:8000;} upstream channels-backend {server 127.0.0.1:8000;} server { listen 192.168.177.128:80; charset utf-8; server_tokens off; access_log /etc/nginx/log/access.log; error_log /etc/nginx/log/error.log; location /static/ {alias /home/reza/Desktop/Project/env/repo/project/mysite/MySiteProject/static/;} location /media/ {alias /home/reza/Desktop/Project/env/repo/project/mysite/MySiteProject/media/;} location / { include uwsgi_params; uwsgi_pass django; try_files $uri @proxy_to_app;} location @proxy_to_app {proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } uwsgi.ini [uwsgi] chdir= /home/reza/Desktop/Project/env/repo/project/mysite/MySiteProject/ processes=10 module=MySiteProject.wsgi:application callable=application daemonize=/home/reza/Desktop/Project/env/repo/networkconfig/log_uwsgi.log socket=127.0.0.1:8037 virtualenv=/home/reza/Desktop/Project/env/ enable-threads=true env=DJANGO_SETTINGS_MODULE=MySiteProject.settings master = true chmod-socket = 660 vacuum = true supervisor.conf [fcgi-program:asgi] socket=tcp://127.0.0.1:8000 directory=/home/reza/Desktop/Project/env/repo/project/mysite/MySiteProject command=daphne -u /run/daphne/daphne%(process_num)d.sock --fd 0 --access-log - --proxy- headers MySiteProject.asgi:application numprocs=1 process_name=asgi%(process_num)d autostart=true autorestart=true stdout_logfile=asgi.log redirect_stderr=true -
Connection with nginx and uwsgi by http
I am struggling with the connection of nginx and django (in the same service docker-swarm) My strategy is like this , run uwsgi http option and 8001 port. (not socket) uwsgi --http :8001 --module myapp.wsgi --py-autoreload 1 --logto /tmp/mylog.log then I confirmed wget http://127.0.0.1:8001 works. but from, nginx, It can't connect somehow. (111: Connection refused) error I googled around and found, this error is related with backend. however I have confirmed. wget http://127.0.0.1:8001 works. Is there any places I need to check??? web_nginx.0.xj2y7mzem9ke@manager | 10.255.0.2 - - [23/Mar/2020:20:40:23 +0000] "GET /favicon.ico HTTP/1.1" 502 568 "http://localhost/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36" "-" web_nginx.0.xj2y7mzem9ke@manager | 10.255.0.2 - - [23/Mar/2020:20:40:23 +0000] "GET / HTTP/1.1" 502 568 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36" "-" web_nginx.0.xj2y7mzem9ke@manager | 2020/03/23 20:40:23 [error] 8#8: *20 connect() failed (111: Connection refused) while connecting to upstream, client: 10.255.0.2, server: 127.0.0.1, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8001/", host: "localhost" web_nginx.0.xj2y7mzem9ke@manager | 2020/03/23 20:40:23 [error] 8#8: *20 connect() failed (111: Connection refused) while connecting to upstream, client: 10.255.0.2, server: 127.0.0.1, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8001/favicon.ico", host: "localhost", referrer: "http://localhost/" web_nginx.0.xj2y7mzem9ke@manager | 10.255.0.2 - - [23/Mar/2020:20:40:23 … -
Django-taggit tag value retrieval and formatting failing
I am trying to implement a tagging process for profiles so you can add your hobbies for example. I have chosen django-taggit as it seemed quite simple and does what I need it to, plus don't really know how to do it myself from scratch. I have managed to make it work to some extent but I am having issues with 3 things: Not really sure what's the best way to control the form field for these tags as I generate the form automatically with widget adjustments in meta function of the form, but it might work fine after resolving the below two issues. When there is no data for the field hobbies (tags) the field gets populated with a single tag of value "[]" as per below image. When I add a tag of "music" and submit the form after I reload the page I get this "[]" as per image. I assumed this will be dealt with by the library, but I cannot see another similar scenario online. My model is: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) hobbies = TaggableManager() My form is: class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['hobbies',] def __init__(self, *args, **kwargs): super(UserProfileForm, … -
Rendering Crispy Form + no submit button
I trying to use crispy layout for my form. I have followed instruction and tutorial but because I am new to Django and python I got lost and it does not render my form as well as submit button. I have model form defined: class nowyPhForm(forms.ModelForm): class Meta: model = Phandlowy fields = ('imie', 'nazwisko', 'email', 'telefon', 'firma', 'filia') def __init__(self, *args, **kwargs): super(nowyPhform, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_action = 'submit_survey' self.helper.add_input(Submit('submit', 'Submit')) self.helper.layout = Layout( Row( Column('imie', css_class='form-group col-md-6 mb-0'), Column('nawisko', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), Row( Column('email', css_class='form-group col-md-6 mb-0'), Column('telefon', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), Row( Column('firma', css_class='form-group col-md-6 mb-0'), Column('filia', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), Submit('submit', 'Sign in') ) and HTML {% load crispy_forms_tags %} {% block content %} <div class="container"> {% crispy form %} </div> {% endblock %} I would appreciate if someone could spot problem. -
Changing the data type of values in the Django model
I have data which is loaded into a dataframe. This dataframe then needs to be saved to a django model. The major problem is that some data which should go into IntegerField or FloatField are empty strings "". On the other side, some data which should be saved into a CharField is represented as np.nan. This leads to the following errors: ValueError: Field 'position_lat' expected a number but got nan. If I replace the np.nan with an empty string, using data[database]["df"].replace(np.nan, "", regex = True, inplace = True), I end up with the following error: ValueError: Field 'position_lat' expected a number but got ''. So what I would like to do, is to check in the model whether a FloatField or IntegerField gets either np.nan or an empty string and replace it with an empty value. The same for CharField, which should convert integers (if applicable) to strings or np.nan to an empty string. How could this be implemented? Using ModelManager or customized fields? Or any better approaches? Sorting the CSV files out is not an option. import pandas as pd import numpy as np from .models import Record my_dataframe = pd.read_csv("data.csv") record = Record entries = [] for e … -
What is the clean way to integrate another service to django
I have a Django 3 application, using an LDAP service class, like this : class LDAPService: def init(self, host: str, user: str, password: str, ssl: bool = True): ... def bind(): # The connection is done here, __init__ just sets values .... def create_ou(base: str, ou_name: str): .... Where (or when) should I initialize the service to use it in views ? The bind step takes about 2 seconds to apply, I can not do it on every request. How can I keep an instance of this class shared, and not done every single time ? I may have a solution using singleton, and/or initializing it in like settings files, but i think there is a better way to do it. I know in production, there may be multiple workers, so multiple instances, but i am ok with it. Another question: How can everything above be done, with connections credentials from a database model (so not at django startup, but at anytime) I am totally new to the django ecosystem, the things i have found about a service layer were all about django models. I think the LDAP connection itself should not be there, only the CRUD methods, but i … -
djangorestframework ModelSerializer serialize model Object but data is empty{}
I use djangorestframework, when I serializer a list of model objects,serializer.data is work, but when I serializer the model object only,serializer.data is the empty{}, why? model: class WindowInfo(models.Model): user = models.ForeignKey(WxAccount, on_delete=models.DO_NOTHING) add_time = models.DateTimeField(default=datetime.datetime.now) ModelSerializer: class WindowInfoSerializer(serializers.ModelSerializer): class Meta: model = WindowInfo fields = '__all__'enter code here view: class WindowInfoViewset(viewsets.GenericViewSet, mixins.CreateModelMixin): serializer = WindowInfoSerializer queryset =WindowInfo.objects.all() authentication_classes = [CustomerAuthentication] def create(self, request: Request, *args, **kwargs): window_info_list = WindowInfo.objects.all() window_info = window_info_list[0] window_info_list = WindowInfoSerializer(data=window_info_list, many=True) window_info_list.is_valid() window_info = WindowInfoSerializer(data=window_info, many=False) window_info.is_valid() print("window_info_list.data:") print(window_info_list.data) print("window_info.data:") print(window_info.data) then console: window_info_list.data: [OrderedDict([('id', 1), ('add_time', '2020-03-24T03:43:13.091961'), ('user', 1)])] window_info.data: {} why the window_info.data is {}? -
Use mongodb as second database for django app
I'm trying to setup two databases for my django app. The first is used for users and the second for any type of user content. The app is dockerized via docker compose. Here's the docker-compose.yaml file version: '3' services: postgres: image: postgres:latest environment: - POSTGRES_PASSWORD=test ports: - "5432:5432" restart: always mongodb: image: mongo:latest command: ["--bind_ip_all"] ports: - "27017:27017" restart: always django: build: . command: bash -c " python service_platform/manage.py makemigrations && python service_platform/manage.py migrate && python service_platform/manage.py runserver 0.0.0.0:8000 " volumes: - .:/code ports: - "8000:8000" depends_on: - postgres - mongodb links: - postgres - mongodb Below are the db settings of django's settings.py DATABASE_ROUTERS = [ 'content_manager.content_db_router.ContentDBRouter', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'postgres', 'PASSWORD': 'test', 'PORT': 5432, }, 'content': { 'ENGINE': 'djongo', 'NAME': 'mongodb', 'CLIENT': { 'host': 'mongodb', 'port': 27017, }, } } Here's the custom router I wrote class ContentDBRouter(object): content_db = 'content' default_db = 'default' def db_for_read(self, model, **hints): if model._meta.app_label == 'content_manager': return self.content_db return None def db_for_write(self, model, **hints): if model._meta.app_label == 'content_manager': return self.content_db return None def allow_migrate(self, db, app_label, model_name=None, **hints): if db == self.content_db: return True elif db == self.default_db: return True else: raise … -
Django: python manage.py runserver abort
I'm trying to set up a repo locally but facing an issue i.e python manage.py runserver command gets aborted as soon as I hit localhost URL (http://127.0.0.1:8000/) error - [1] 7398 abort python manage.py runserver Django version 1.6.6 Python 2.7 OS -> MacOS Catalina (10.15.3) Database postgres (PostgreSQL) 12.2