Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ForeignKey reverse Query
I have 3 models related witch each other with FK: class MainEvent(models.Model): name = models.CharField(max_length=512, blank=True) class Event(models.Model): main_event = models.ForeignKey(MainEvent, blank=True, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=512, blank=True) class SubEvent(models.Model): event = models.ForeignKey(Event, blank=True, null=True, on_delete=models.CASCADE) done = models.BooleanField(default=False) What i need is to create single reverse query on model MainEvent that holds related Events and Subevents. I will use this with Q for filter multiple options. For example: there are 2 MainEvents, each of them have 2 or more Events and each Event have 2 or more Subevents. I'm trying to create single Query something like this: [MainEvent_1:[Event_1:[Subevent_1,Subevent_2,...],Event_2:[Subevent_5,...]], MainEvent_2:[Event_2:[Subevent_2,..]]] For now I'm creating dictionary that holds desired output, but with this i con't use Q relations like & or |. At the end i'm using this data in template table to show all events and filter them: desired table structure: main event_1: event_1: subevent_1 subevent_2 event_2: subev... ........... main event_2: event_2: subev.... Thank you for your time. -
Auto update slug field in UpdateView
I have a simple blog where the post model contains a slug field that is prefilled with the post title. I would like to know how to get this slug updated in the background when the user updates a post title in the viewUpdate: models.py class Post(models.Model): title = models.CharField(max_length=150) content = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( CustomUser, on_delete=models.CASCADE ) slug = models.SlugField(unique=True) def get_absolute_url(self): return reverse('post_detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) urls.py urlpatterns = [ path('post/<slug:slug>/', views.PostDetailView.as_view(), name='post_detail'), ] views.py class PostUpdateView(UpdateView): model = Post fields = ['title', 'content', 'tags'] I assume I should add something else to view.py in order to have the slug updated but after hours googling it, I could not find it. Please let me know if you need more information. It is quite a simple question so I am not sure if I should provide anything else. -
I need Help in displaying data imported from database in form of tables using django
I am making a website in which i need to display data in form of tables. I have 2 filters in form select tag which will filter the data and display in then and there in the table. //my views.py def synop_view(req): return render(req,'synops/viewsynop.html') //my html code <div class="col-sm-3 lead ml-5 mt-4"> Select Date <input type="date" class="custom-select" name="synopdate" id="myDate" > </div> <div class="col-sm-3 lead mt-4 "> UTC <select class="custom-select" name="time" id="stime"> <option value="" disabled selected>Choose your option</option> <option value="0000">0000 UTC</option> <option value="0300">0300 UTC</option> <option value="0600">0600 UTC</option> <option value="0900">0900 UTC</option> <option value="1200">1200 UTC</option> <option value="1500">1500 UTC</option> <option value="1800">1800 UTC</option> <option value="2100">2100 UTC</option> </select> </div> </div> -
Please i want to create a folder on a web page using django
I want to create a folder on a web page using django but i am unable to find answers. Please i need help, thank you in advance. I have tried searching online but i could not find something relating to that -
Django Orm , include function like asp.net core
class Genre(models.Model): name = models.CharField(max_length=255) class Movie(models.Model): title = models.CharField(max_length=255) release_year = models.IntegerField() number_in_stock = models.IntegerField() daily_rate = models.FloatField() genre = models.ForeignKey(Genre, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) i have this kind of model i want to query the data to become like this. how do i do it like this ??? [ { "id": 3, "title": "123123", "release_year": 4, "number_in_stock": 12, "daily_rate": 1.234, "genre": { genre_id: 4, name: "Action }, "date_created": "2019-10-30T08:33:59.846Z" } ] -
how to start the hamlpy
I try to use hamlpy for my project. I made the following settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', ## 'hamlpy', 'testapp', ] TEMPLATE_LOADERS = ( 'hamlpy.template.loaders.HamlPyFilesystemLoader', 'hamlpy.template.loaders.HamlPyAppDirectoriesLoader', 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], ## 'APP_DIRS': True, 'OPTIONS': { 'loaders': TEMPLATE_LOADERS, 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] my view: haml = lambda request: render(request,"article.haml",{}) my template: #profile .left.column #date 2010/02/18 #address Toronto, ON .right.column #bio Jesse Miller But the result page output is one line: profile .left.column #date 2010/02/18 #address Toronto, ON .right.column #bio Jesse Miller I mean nothing: the template has handled as usually django-template. What is the secret for hamlpy works on django? P.S: Django 1.11 -
python django bokeh need to select picture from database instead of path
source_glyph = AjaxDataSource( data_url=url_pic, polling_interval=STREAMING_INTERVAL, adapter=adapter_picture, method="GET" ) source_glyph.data = dict( url=[picture_path], x1=[int(picture_x_position)], y1=[int(picture_y_position)], w1=[int(width)], h1=[int(height)], ) image1 = ImageURL( url="url", x="x1", y="y1", w="w1", h="h1", anchor="center", global_alpha=0.3 ) p1.add_glyph(source_glyph, image1) picture path contains f'http://127.0.0.1:8000/media/pictures/{only_files[0]}' I need to read picture from database some how instead of from a folder. How to do it -
Django model save scikit-learn model to file field error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte
I have this model and internal function that's going to create a scikit-learn model, train it save it then link it to a filefield so I can retrieve it and use it later to make predictions. class StockTrainModel(models.Model): trained_model = models.FileField(upload_to="training_model", blank=True) ... def __str__(self): return str(self.stock) def train_model(self): ... clf = RandomForestClassifier(max_depth=2, random_state=0) clf.fit(X_train, y_train) self.training_score = clf.score(X_test, y_test) * 100 filepath = 'media/uploads/training_model/{0}.sav'.format(self.stock.symbol) joblib.dump(clf, filepath) f = open(filepath) self.trained_model.save('{0}.sav'.format(self.stock.symbol), File(f, 'rb')) return self.trained_model the problem is as shown in the error below it fails with a utf-8 error encoding error and in this case I'm not exactly sure which encoding joblib that's scikit-learn model uses to encode the file, I assumed it's just bytes and tried using rb "read bytes" on the file open but it still returns the same error. --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) <ipython-input-5-3b847b21decc> in <module> ----> 1 train_model.train_model() ~/code/coder/common/models.py in train_model(self) 159 160 f = open(filepath) --> 161 self.trained_model.save('{0}.sav'.format(self.stock.symbol), File(f, 'rb')) 162 163 return self.trained_model .... ~/code/envs/coder/lib/python3.6/codecs.py in decode(self, input, final) 319 # decode input (taking the buffer into account) 320 data = self.buffer + input --> 321 (result, consumed) = self._buffer_decode(data, self.errors, final) 322 # keep undecoded input until the next … -
Python fetching data and showing to my django website
I am developing a website and implementing a search system/ I am just want to fetch data from here: https://www.ahpra.gov.au/Registration/Registers-of-Practitioners.aspx and show the data on my django website. I don't want to store the data in DB I am not getting how to achieve this. If you search on this website: https://www.ahpra.gov.au/Registration/Registers-of-Practitioners.aspx with a keyword like smith it will show you huge data but no URL changes, this is the challenge to scrape So I think I need to scrape the data with selenium? or any other best way to achieve my goal? I need expert suggestion, what is the best way to do it? -
Django allauth and custom 404 page
My question is partly two. Question 1 (allauth): I have set allauth for my project to accept facebook login which works well. However i will like the user to fill a form before he complete his signup. To do this i added the following to my profile app : class CustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') role = forms.CharField(max_length=30, label='Role( client or pilot )',) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.role = self.cleaned_data['role'] user.save() return user seetings.py ACCOUNT_FORMS = { 'signup': 'profile.forms.CustomSignupForm', } **allauth settings:** SITE_ID = 1 After the facebook signin, it only ask for email and user name. Question 2(404): I have launched my app on digital ocean and i have set up a custome 404, 500, and 403 error page in my pages app: def handler404(request, exception, template_name="404.html"): response = render_to_response("404.html") response.status_code = 404 return response def handler403(request, exception, template_name="403.html"): response = render_to_response("403.html") response.status_code = 403 return response def handler500(request, exception, template_name="500.html"): response = render_to_response("500.html") response.status_code = 500 return response Project urls.py handler404 = 'pages.views.handler404' handler403 = 'pages.views.handler403' handler500 = 'pages.views.handler500' The 403 page works however both the 404 and 500 fails to work. -
Why .query() function not working on Django ORM query?
As I already know that using .query.__str__() , we can get sql equivalent query from Django ORM query. e.g : Employees.objects.filter(id = int(id)).query.__str__() Above code working well & I am able to get sql equivalent query but when I am using same on below query I am getting error like below. Employees.objects.filter(id = int(id)).first().query.__str__() AttributeError: 'Employees' object has no attribute 'query' Why now I am getting error, any suggestions ? -
Django - Conditional Rendering In Templates
I need some help conditionally rendering data in a modal pop up window on my site. What I want to do: When the user clicks on the "make reservation" button, I want to display this in the modal window <h3 style="margin-top:20px;">Choose dates</h3> <div style="margin-top:20px;" class="pick-dates-div"> <form method="GET" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="form-btn save btn btn-default">Make A Reservation</button> </form> <button style="margin-top: 25px;" class="btn-primary btn-block btn-lg" data-toggle="modal" data-target="#inquiryModal">More Questions ?</button> </div> Then the user can pick the dates from the date picker and press the "make a reservation" button ( which is a GET request ), the page refreshes and I want to display only this in the same modal window : <h1>Start Date: {{ date_start }}</h1> <h1>End Date: {{ date_end }}</h1> <h1>Price Per Day: ${{ price_per_day }}$</h1> <h1>Total: ${{ total_price }}$</h1> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <a href=""> <button href="www.facebook.com" type="submit" class="form-btn save btn btn-default">Confirm Reservation</button></a> </form> After that the user submits the form ( POST request ) and I want to display a text : <h3> Thank you for your reservation </3> What would be the ideal way to achieve this ? Thank you stack -
How to send data in POST request where the data is not entered by the user in Django
I am trying to make a watchlist for stocks for my website. The data i.e name of the Company and the stock price is already being displayed on the webpage. I want that the user should just click on a button on the same webpage and it adds the data to the watchlist of the user. This is for a website for stock analysis. I dont know how to do this. PS- I'm new to coding Watchlist Model: class WatchList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) watchlist = models.CharField(max_length=300, default='') price = models.IntegerField(default='') html: {% extends 'homepage/layout.html' %} {% block content %} {% load static %} <head> <title>Technical Analysis</title> <link rel="stylesheet" href="{% static 'tech_analysis/tech_analysis.css' %}"> </head> <div class="line"></div> <div class="head"> Technical Analysis </div> <div class="coname"> <ul class="ticker_table"> <li class="ticker_name">{{ ticker }}-</li> <li class="ticker_price">{{ price }}</li> <li class="diff_green">{{ diff_green }}</li> <li class="diff_red">{{ diff_red }}</li> </ul> <form action="{% url 'bsh_user:Userpage' %}" method="post"> {% csrf_token %} <input class="watchlist" type="submit" value="Add To Watchlist +"> </form> </div> the information such as {{ticker}} and {{price}} is the data that is to be posted to the model and displayed to the user on a different html. Expected outcome is to add a company and its price to the watchlist … -
Internal Server Error for User.objects.get(email=email)
I want to check if a given email exists in auth_user of django First I import from django.contrib.auth.models import User In the controller, I test like this: user_by_email = User.objects.get(email=email) # internal server error at this point. if user_by_email is not None: return HttpResponseBadRequest() But this line returns internal server error. Than I created a new row in auth_user manually, it worked as it should be. -
Compare datetime values in django models
I have an Offer model that has a datetime field and I have two records in the database >>> oldOffer.offerDate datetime.datetime(2019, 10, 29, 15, 19, 43, 755325) >>> currOffer.offerDate datetime.datetime(2019, 10, 29, 15, 20, 2, 456100) >>> Offer.objects.filter(offerDate__lt= currOffer.offerDate) <QuerySet []> >>> Offer.objects.filter(offerDate__gt= currOffer.offerDate) <QuerySet [<Offer: Offer object (5)>, <Offer: Offer object (6)>> The currOffer.offerDate is clearly greater than the oldOffer.OfferDate. Then why am I getting an empty result with the __lt clause? Also why do I get both the oldOffer (object 5) and currOffer (object 6) when I use __gt clause? What am I doing wrong? Thanks in advance -
How to confirm purchase with app using django backend
i'm thinking of having an app to check the server if it's been paid or not? if it's paid so user can use the app if not they need to pay does it work with a simple api? (i'm almost new to django) thanks -
Insert into a model with two foreign keys on a post save signal
I hope that the title of my message will be precise enough, if it is not the case I apologize in advance. I do not know how to do the following thing: I have three models: \model class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True,null=True) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True) class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, **kwargs): if created: StudentsEnrolledSubject.objects.create(Students_Enrollment_Records=instance.Student_Users, Subject_Section_Teacher = SubjectSectionTeacher.Employee_Users) I just want that when the admin update the student enrollment record and must be added automatically in StudentsEnrolledSubject -
Error collection and propagation in Django serializers
I am struggling with collecting exceptions when using multiple Django serializers. Here is the situation. With multiple serializers, I want the last serializer (such as Beta in the following example)to collect all errors/exceptions generated while invoking the others. However, if a serializer higher in the chain (such as Alpha)raises an exception, the server stops and reports it and the view class was even reached. What should I do to propagate these exceptions to Beta and eventually send them to the front though the view? class Alpha(Serializer): def validate(self, user_data): if something wrong: raise Exception(..) return user_data class Beta(Serializer): def validate(self, data): serializer_alpha = Alpha(data['user']) if serializer_alpha.is_valid(): [do something] else: raise Exception(serializer_alpha.errors) return data In a view, the attempt is to report all the errors/exceptions that took place along the validation chain, class ParticularAppView(APIView): def post(self, request, **kwargs): serializer = Beta(data=request) if serializer.is_valid(): try: [do something] Response(response, ...) except Exception as e: Reponse(serializer.errors, ...) -
Django Apache error: No module named 'encodings'. Windows server 2008 R2 Standard
I clone repo from git. I create venv: python -m venv myenv /myenv/scripts/activate.bat pip install -r requirements.txt pip install mod_wsgi-4.6.5+ap24vc14-cp36-cp36m-win_amd64.whl if i run from myvenv that: python manage.py runserver it's work! if I run from apache, I have a error: [Wed Oct 30 10:51:18.732028 2019] [mpm_winnt:notice] [pid 352:tid 168] AH00455: Apache/2.4.41 (Win64) mod_wsgi/4.6.5 Python/3.6 configured -- resuming normal operations [Wed Oct 30 10:51:18.732028 2019] [mpm_winnt:notice] [pid 352:tid 168] AH00456: Apache Lounge VS16 Server built: Aug 9 2019 16:46:32 [Wed Oct 30 10:51:18.732028 2019] [core:notice] [pid 352:tid 168] AH00094: Command line: 'httpd -d C:/Apache24' [Wed Oct 30 10:51:18.732028 2019] [mpm_winnt:notice] [pid 352:tid 168] AH00418: Parent: Created child process 1748 Fatal Python error: Py_Initialize: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' Current thread 0x00000354 (most recent call first): [Wed Oct 30 10:51:23.677228 2019] [mpm_winnt:crit] [pid 352:tid 168] AH00419: master_main: create child process failed. Exiting. below httpd.conf: LoadFile "c:/<>/python/python36/python36.dll" LoadModule wsgi_module "c:/envs/myproject/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIScriptAlias / "c:/<myproject>/wsgi.py" WSGIPythonHome "c:/envs/myproject" WSGIPythonPath "c:/<myproject>" Alias /static/ "c:/<myproject>/static/" <Directory "c:/<myproject>/static"> Require all granted </Directory> <Directory c:/<myproject>> <Files wsgi.py> Require all granted </Files> </Directory> <Directory c:/<myproject>/attachments> Require all granted </Directory> I set PYTHONHOME and PYTHONPATH as "C:\Users\user\AppData\Local\Programs\Python\Python36;C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts" I looked many question, example: Fatal Python error … -
Read data from external mysql database and save it into default database in django
I have 2 database connections(default and external). I want to read the data from the external database tables and save it into the default database table. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'hello', 'USER':'root', 'PASSWORD': '', 'HOST': '127.0.0.1', }, 'external_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'hello_external, 'USER':'root', 'PASSWORD': '', 'HOST': '127.0.0.1', } } routers.py """ A router to control all database operations on models in the myapp2 application """ def db_for_read(self, model, **hints): return 'external_db' def db_for_write(self, model, **hints): return 'default' def allow_syncdb(self, db, model): return db == 'default' def allow_migrate(self, db, app_label, model_name=None, **hints): return (db == 'default') -
Like button in django is not working properly in django
I have added like and dislike button to Song post When like object is not created if some click on like it is showing intigrity error if like object is already there then it is not rendering that to template. models.py Codes in models.py class Song(models.Model): song_title = models.CharField(max_length=25) album = models.ForeignKey(Album, related_name='album_name', on_delete=models.CASCADE, blank=True) singer = models.ManyToManyField(Singer, blank=True) language = models.CharField(max_length=25) class VoteManager(models.Manager): def get_vote_or_unsaved_blank_vote(self,song,user): try: return Vote.objects.get(song=song,user=user) except ObjectDoesNotExist: return Vote(song=song,user=user) class Vote(models.Model): UP = 1 DOWN = -1 VALUE_CHOICE = ((UP, "👍️"),(DOWN, "👎️"),) like = models.SmallIntegerField(choices=VALUE_CHOICE) user = models.ForeignKey(User,on_delete=models.CASCADE) song = models.ForeignKey(Song, on_delete=models.CASCADE) voted_on = models.DateTimeField(auto_now=True) objects = VoteManager() class Meta: unique_together = ('user', 'song') views.py Codes in views.py class SongDetailView(DetailView): model = Song template_name = 'song/song_detail.html' def get_context_data(self,**kwargs): ctx = super().get_context_data(**kwargs) if self.request.user.is_authenticated: vote = Vote.objects.get_vote_or_unsaved_blank_vote(song=self.object, user = self.request.user) if vote.id: vote_url = reverse('music:song_vote_update', kwargs={'song_id':vote.song.id,'pk':vote.id}) else: vote_url = reverse('music:song_vote_create', kwargs={'song_id':vote.song.id}) vote_form = SongVoteForm(instance=vote) ctx['vote_form'] = vote_form ctx['vote_url'] = vote_url return ctx class SongUpdateView(UpdateView): form_class = SongVoteForm queryset = Song.objects.all() def get_object(self,queryset=None): song = super().get_object(queryset) user = self.request.user return song def get_success_url(self): song_id = self.kwargs.get('song_id') return reverse('music:song_detail', kwargs={'pk':song_id}) class SongVoteCreateView(View): form_class = SongVoteForm context = {} def post(self,request,pk=None,song_id=None): vote_obj,created = Vote.objects.get_or_create(pk=pk) song_obj = Song.objects.get(pk=song_id) vote_form = SongVoteForm(request.POST, … -
Error: pg_config executable not found. even though I have added the path to pg_config on environment variable
I am trying to setup saleor (Django based). I did a "python -m pip install -r requirements.txt" as stated on the website. Things go well until the installation Collecting psycopg2-binary==2.8.3 and then error is thrown. I have Postgre installed and I am on windows. I also have added the path to pg_config on my environment variable since it says pg_config executable not found. I am not sure how to proceed. Here is the error that is shows up: ERROR: Command errored out with exit status 1: command: 'C:\Users\ASPIRE\AppData\Local\Programs\Python\Python38-32\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\ASPIRE\\AppData\\Local\\Temp\\pip-install-d7c359c_\\psycopg2-binary\\setup.py'"'"'; __file__='"'"'C:\\Users\\ASPIRE\\AppData\\Local\\Temp\\pip-install-d7c359c_\\psycopg2-binary\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\ASPIRE\AppData\Local\Temp\pip-install-d7c359c_\psycopg2-binary\pip-egg-info' cwd: C:\Users\ASPIRE\AppData\Local\Temp\pip-install-d7c359c_\psycopg2-binary\ Complete output (23 lines): running egg_info creating C:\Users\ASPIRE\AppData\Local\Temp\pip-install-d7c359c_\psycopg2-binary\pip-egg-info\psycopg2_binary.egg-info writing C:\Users\ASPIRE\AppData\Local\Temp\pip-install-d7c359c_\psycopg2-binary\pip-egg-info\psycopg2_binary.egg-info\PKG-INFO writing dependency_links to C:\Users\ASPIRE\AppData\Local\Temp\pip-install-d7c359c_\psycopg2-binary\pip-egg-info\psycopg2_binary.egg-info\dependency_links.txt writing top-level names to C:\Users\ASPIRE\AppData\Local\Temp\pip-install-d7c359c_\psycopg2-binary\pip-egg-info\psycopg2_binary.egg-info\top_level.txt writing manifest file 'C:\Users\ASPIRE\AppData\Local\Temp\pip-install-d7c359c_\psycopg2-binary\pip-egg-info\psycopg2_binary.egg-info\SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also … -
Choice of tech stack Django + Dojo + Dijit (Python-based) vs Express for AI-based application
Faced with a tech stack choice and appreciate any inputs. Application: user uploads files, backend processes the files, sends it to a AI-based tensor flow pipeline. Result displayed to end-user. Choice 1: Lang: python everywhere Framework: Django + Dojo + dijit DB: Postgres SQL Backend AI: Tensorflow Hosting: Google Cloud Choice 2: Lang: hybrid: javascript + python Framework: Express + modules, node.js DB: nosq mongodb Backend AI: Tensorflow Hosting: AppEngine My concerns with Choice 1 django stack - Django has power, but not a easy learning path, and deployment issues exist (e.g django + bitnami stack highly complex managed cloud instance) - Deployed a sample app, web pages seem to render twice, as the dojo, digit frameworks seem to load scripts and render so the per page load time is bad - UX Themes limitation and looks a bit arcane 2000ish - Dojo libraries are big 12K files making it hard to deploy on Appengine so u have to go the managed cloud instance route - Advantages: all in one language, and integration over command line with python and subprocess.call to call tensor flow great. Free admin with django awesome - do I have flexiblity to use a noSQL databae … -
Django signals foreignkey
model.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Remarks = models.TextField(max_length=500, null=True, blank=True) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True) class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True) I code this in my model def studentenrolled(sender,instance, **kwargs): if kwargs['created']: ireceived = StudentsEnrolledSubject.objects.create(Students_Enrollment_Records=instance.Student_Users, Subject_Section_Teacher=SubjectSectionTeacher.Employee_Users) post_save.connect(studentenrolled, sender=StudentsEnrollmentRecord) this is the error I Got my error I just want that everytime the admin input/update the StudentsEnrollmentRecord.Section and StudentsEnrollmentRecord.Course, it will automatic search the Employee_Users from SubjectSectionTeacher and it will save automatically in StudentsEnrolledSubject I dont know if i am doing right in django signal, please help me! -
Django logging is empty
I'm having problem on why on earth just happen after I added a formatter on the LOGGING configuration the logging file is empty. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{asctime} [{module}]:: {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'handlers': { 'console':{ 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'file.DEBUG': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'logs/debug.log', 'maxBytes' : 1024*1024*10, 'backupCount': 10, 'formatter':'verbose' }, 'file.INFO': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'logs/info.log', 'maxBytes' : 1024*1024*10, 'formatter':'verbose' }, 'file.ERROR': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'logs/error.log', 'maxBytes' : 1024*1024*10, 'backupCount': 10, 'formatter':'verbose' }, }, 'loggers': { 'django.request': { 'handlers': ['file.DEBUG'], 'level': 'DEBUG', 'propagate': True, }, 'django': { 'handlers': ['file.INFO'], 'level': 'INFO', 'propagate': True, }, 'django': { 'handlers': ['file.ERROR'], 'level': 'ERROR', 'propagate': True, }, }, } Now all the outputed debug file are empty except for the error file which I tested on the view with this code import logging logger = logging.getLogger('django') logger.info('tests') logger.error('tests') logger.debug('tests') logger.debug('tests') logger.error('tests') logger.info('tests') Only the error is being logged on the file, why is this? Im using the new version of django which is 2.2