Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Transform Queryset Into string
I have a Django / Python QuerySet that Looks like this: [{'first_name': 'hans', 'last_name': 'baust'}] And I would like to only have something like variable name1 that contains 'hans' variable name2 that contains 'hans' I cannot make it with the current Google results... -
Jinja: combine several templates into one single document
I'm working with Django and want to dynamically merge several jinja templates into one single document. Each of those templates is a complete, independent document, that is, it contains all the markup it needs to be rendered individually. Do you know if this is possible, or if Jinja offers a special API or method for this kind of operation? -
How to build a queryset in a specific order in Django
I'm trying to list profiles of users. I want to list them in such a way that profiles with same city of the user should come first, then next priority should be state, then country, and finally, rest of the profiles. This is what I have tried. profiles_city = Profile.objects.filter(city=current_user.city) profiles_state = Profile.objects.filter(state=current_user.state) profiles_country = Profile.objects.filter(country=current_user.country) profiles_all = Profile.objects.all() profiles = (profiles_city | profiles_state | profiles_country | profiles_all).distinct() But it is yielding the same result as Profile.objects.all() Please help me. thanks in advance -
Hide a field from a django ModelForm depending on user's profile
I have a form that has two fields (mail and status). I want to have the status field hidden only when the user has a profile not equal to "tech" so that the user cannot change its value in that case. What I was trying to do, but I still didn't get it to work since it throws me TypeError error: __init __ () got an unexpected keyword argument 'user', is to overwrite the __init __ () method of RequestForm in forms.py and on the other hand, overwrite the get_form_kwargs () method to pass the user to the form. I post the code that I understand relevant: views.py: ... class RequestUpdate(UpdateView): model = Request form_class = RequestForm template_name = 'request/request_form.html' success_url = reverse_lazy('request:request_list') def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['user'] = self.request.user return kwargs forms.py: class RequestForm(forms.ModelForm): class Meta: model = Request fields = [ 'mail', 'status', ] labels = { 'mail': 'E-Mail (including @domain.example)', 'status': 'Request's status:' } widgets = { 'mail': forms.EmailInput(attrs={'class': 'form-control'}), } def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super().__init__(*args, **kwargs) if self.user.is_tech == False: self.fields.pop('status') models.py ... class Request(models.Model): mail = models.CharField(max_length=50) states = [('1','Pending'), ('2','In process'), ('3','Done')] status = models.CharField(max_length=50, choices=states, default='1') user = … -
How to make an api call from my django view
I'm using python 3.6.8 with django 2.2.5. I've built a rest api and I want to call it via the url using my django view login_request() function. Here is the source code: def login_request(request): """ This function is used to login all users except the admin of the entire site. It makes an api call to the LoginView defined in commons.apiviews with the necessary parameters and renders the necessary html file accordingly. It gets the necessary data from the request.session variable. """ if request.method == 'POST': # login_response = request_library.Response() try: user_data = { "username": request.POST.get('username'), "password": request.POST.get('password') } login_response = request_library.post( "http://localhost:8055/commons/login/", data=request.POST, headers={ 'content-type': "application/x-www-form-urlencoded" }, timeout=(3, 6) ) login_response.raise_for_status() except Exception as e: # TODO find a better thing to do with the exception with open('login_tries.txt', 'a') as login_response_objects: login_response_objects.write(str(e) + "\t" + str(request.body) + "\n\n") else: if login_response is not None: # user_token = login_response.token messages.info(request, f"You are now logged in as {request.data.get('username')}") return redirect('ui/dashboard.html') else: return HttpResponse("didn't work") return render(request=request, template_name="ui/login.html", context={}) What it's supposed to do is, whenever http://localhost:8055/commons/login/ is POSTed to with username & password it will return a 200 and an authorization token as a response. The above is being used by … -
How to connect my postgresql database with my django project?
When I run the command "pg_ctl -D -l logfile start", I have this result : waiting for server to start.... stopped waiting pg_ctl: could not start server Examine the log output And when I ckecked the logs, I have this : check-logs And this is my configuration: settings.py postgresql.conf pg_hba.conf Do I change the .conf files ? And which parameters ? Thank you for you answers ! -
How to sort list of dictionaries in Python
I have a list of dictionaries in Pyhton as follows: images = [{'uri': 'https://some-link.blob.core.windows.net.net/devthumbnails/1024x768/64/41/98/64419888297779407561461629073227065160696285270116603463558823470505654333611.jpg', 'position': '0'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/33/44/41/33444169622672594337676840600346050570907940224888845885580705086781040628903.jpg', 'position': '1'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/41/46/99/41469935475840270004889223861351938003980938652350786820222101550878440209095.jpg', 'position': '2'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/58/75/58/5875586317181716679126235880198721021684963481995594779485630886902274081554.jpg', 'position': '3'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/43/49/66/43496617617402984595952294447831932918405619473544645594784712841815014159696.jpg', 'position': '4'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/58/02/34/58023409863921180862667204492888551278254010639571762445601939880620855964505.jpg', 'position': '5'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/36/22/76/36227680451273880975070000838700274536225673420153023620631555589946521174102.jpg', 'position': '6'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/25/08/19/25081934413799694457632686505539828478363116795387601261763375409872686844488.jpg', 'position': '7'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/29/69/32/29693252042243727029651750357989431990778953906071901135228406135133977694240.jpg', 'position': '8'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/32/08/12/32081296724310348807184322021859931042996444008194149989050172920699516702708.jpg', 'position': '9'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/78/32/05/78320563911470703705431807857066302926786080992451285767704219765878587895294.jpg', 'position': '10'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/45/68/68/45686886529184531303217514851187276286410962612950239302976824977433885355299.jpg', 'position': '11'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/72/59/00/7259007439354083322229206921563369468125207106159648770203873465284114242890.jpg', 'position': '12'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/84/48/54/84485459564719601932735074276164902175816462482914733108723651993560201088913.jpg', 'position': '13'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/10/28/77/102877279417898628351098113431759126412045721643126079051218817213834246455153.jpg', 'position': '14'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/39/83/38/39833822893039666936949954403817914899073341336875871633644019565696649530535.jpg', 'position': '15'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/99/45/89/99458973667381587321791276054667596349042589326181154771316565893893148706844.jpg', 'position': '16'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/82/61/29/82612936862475837022828306892947119148350841132548959316321620668433031577983.jpg', 'position': '17'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/11/19/56/111956100385260490476900173411198572352351708852063055906233069090064975146790.jpg', 'position': '18'}] I want to sort it and I want that the new list is as follows: [first_three_elements, last_three_elements, the_rest]. I've tried with something as follows: first_three = images[0:3] the_rest = images[3:int(len(images) - 3)] last_three = images[(int(len(images) - 3)):int(len(images))] result = first_three + last_three + the_rest But I get an error: unhashable type: 'slice' unhashable type: 'slice' unhashable type: 'slice' Any idea how to solve it? -
How to add like button in class based List view in django
I have added like button in detail view but could't able make the logic to add like button in List View. I have commented out the logic which I have used in Detail View below which is failed to create like button in List View. can somebody help me with the please. model.py Codes in models.py class AlbumVoteManager(models.Manager): def get_vote_or_unsaved_blank_vote(self,album,user): try: return Vote.objects.get(album=album,user=user) except ObjectDoesNotExist: return Vote(album=album,user=user) class AlbumVote(models.Model): UP = 1 DOWN = -1 VALUE_CHOICE = ((UP, "👍️"),(DOWN, "👎️"),) like = models.SmallIntegerField(null=True, blank=True, choices=VALUE_CHOICE) user = models.ForeignKey(User,on_delete=models.CASCADE) album = models.ForeignKey(Album, on_delete=models.CASCADE) voted_on = models.DateTimeField(auto_now=True) created_on = models.DateTimeField(auto_now_add=True) objects = AlbumVoteManager() class Meta: unique_together = ('user', 'album') form.py Codes in form.py class AlbumVoteForm(forms.ModelForm): class Meta: model = AlbumVote fields = ['like'] views.py Codes in views.py class AlbumListView(ListView): model = Album paginate_by = 5 # def get_context_data(self,**kwargs): # ctx = super().get_context_data(**kwargs) # if self.request.user.is_authenticated: # vote = AlbumVote.objects.get_vote_or_unsaved_blank_vote(album=self.object_list.object, user = self.request.user) # if vote.id: # vote_url = reverse('music:album_vote_update', kwargs={'album_id':vote.album.id,'pk':vote.id}) # else: # vote_url = reverse('music:album_vote_create', kwargs={'album_id':self.object_list.object.id}) # vote_form = AlbumVoteForm(instance=vote) # ctx['vote_form'] = vote_form # ctx['vote_url'] = vote_url # return ctx album_list.html Codes in album list view. <div class="container"> {% if object_list %} {% for album in object_list %} <div class="card … -
How to tell the cache_page decorator to use different cache_keys with regards to the Accept header?
I realized that the cache_page decorator will cache text/html or application/json responses and return one for the other without noticing. I'd like to give cache_page a list of header to use to generate a cache key so that it can take it into account. -
django-q does not stop with Ctrl-C
i installed django-q version 0.9.4 but i can not stop qcluster with Ctrl+C. Q_CLUSTER = { 'name': 'DjangORM', 'sync' : False, 'orm': 'default', 'retry': 18000, } 15:43:57 [Q] ERROR reincarnated worker Process-1:8 after death 15:43:57 [Q] ERROR reincarnated worker Process-1:17 after death 15:43:57 [Q] ERROR reincarnated worker Process-1:19 after death 15:43:57 [Q] ERROR reincarnated monitor Process-1:21 after sudden death 15:43:58 [Q] ERROR reincarnated pusher Process-1:22 after sudden death 15:43:58 [Q] ERROR reincarnated worker Process-1:14 after death 15:43:58 [Q] ERROR reincarnated worker Process-1:20 after death 15:43:59 [Q] ERROR reincarnated worker Process-1:18 after death 15:44:01 [Q] INFO Process-1:24 ready for work at 9312 15:44:01 [Q] INFO Process-1:23 ready for work at 4432 -
Customer search for an IT company
We are a small team of brilliant and self-motivated persons. For over 7 years, Owlab has been a business-oriented software engineering company committed to helping businesses kickstart, develop, and succeed. With profound technological expertise in a range of business domains such as financial services, healthcare, retail, and entertainment, Owlab implemented innovative ideas that allowed businesses - from startups to mid-sized and large companies - to scale, evolve, and prosper. Our quality policy includes functionality, usability, security, and crowd testing. We transfer all copyrights once the project is done. We will be able to sign NDA, and we never disclose information about the project. We provide the following services: Design Development: UI/UX Wireframing with Balsamiq/Sketch UI/UX Design with Photoshop/Sketch Website Development: Backend on Django/Python or PHP Frontend on React JS (or simple jQuery if requested) Restful API development on Django/Python Web Scraping/Crawling, Data collection on Python Mobile App Development: iOS Native Apps using Swift programming language Android Native Apps using Java programming language We are a small team of brilliant and self-motivated persons. For over 7 years, Owlab has been a business-oriented software engineering company committed to helping businesses kickstart, develop, and succeed. With profound technological expertise in a range of … -
My url not reading my function in views.py in DJANGO (found similar question not able to trace my issue)
mysite/urls.py from django.contrib.auth import views from django.views.generic.base import TemplateView urlpatterns = [ url('update_db/(<dbname>)/', include('polls.urls')), url(r'^admin/', admin.site.urls), url('mysite/login/', auth_views.LoginView.as_view(),name='login'), url(r'^fetch/',include('polls.urls')), url('mysite/logout/$', auth_views.logout, name='logout'), ] polls.urls.py from django.conf.urls import url from . import views from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse urlpatterns = [ url('update_db/(?P<dbname>\w+)/$', login_required(views.MyView.get), name='x'), url('', login_required(views.IndexView.as_view())), ] fetch.html <td><a href="{% url 'x' dbname=schdule.5 %}/?next='fetch'">click</a></td> polls/views.py from django.shortcuts import render from django.views.generic import TemplateView , ListView from django.views.generic.edit import UpdateView # Create your views here. from django.http import HttpResponse from .models import Item , DbRestorationLogDetails class MyView(UpdateView): logger.error('Something went wrong!') print "THANKS FOR UPDATING" template_name='fetch.html' model = DbRestorationLogDetails fields =['verification_status'] def get(self,request, dbname): usname=request.user print usname print dbname if request.method == "GET": dblog = DbRestorationLogDetails.objects.get(dbname=dbname) dblog.verification_status = 'Verified' print dblog.verification_status dblog.save() #.update(dblogdetails.verification_status = 'Verified') return HttpResponseRedirect(request.GET.get('next')) NOTE: NOT able to reach to MyView.get() and no db update happening. I assume my code is not able to read my function. -
Update another Model value through DRF perform_create (viewset) or post_save signal of Model
I have a model which's field values are updated through other models. For example, Model (Post), and creating a Post updates the post_exist value of Model (Onboarding). The method that updates the post_exist value is put into a redis queue as I dont want it to be blocking. Which of the following two ways is the best way considering speed and safety: The post is created using Django Rest Framework. The method that updates the post_exist value (in redis queue) is called in the perform_create method of the Post its Viewset or The method that updates the post_exist value (in redis queue) is called in the post_save signal of the Post model. -
requirements.txt Issues while deploying Django on AWS Elastic Beanstalk
I am trying to deploy a Django APP on AWS Elastic Beanstalk, but i have been dealing with this requirements.txt file invalid error for hours. Please any help would be apppreciated Erros Trace: 019-11-04 11:54:26 INFO createEnvironment is starting. 2019-11-04 11:54:27 INFO Using elasticbeanstalk-us-west-2-607492160452 as Amazon S3 storage bucket for environment data. 2019-11-04 11:54:50 INFO Created security group named: sg-07294ef34f2e0aaa2 2019-11-04 11:55:06 INFO Created load balancer named: awseb-e-y-AWSEBLoa-9P7Z3Q0VIKKW 2019-11-04 11:55:06 INFO Created security group named: awseb-e-yrxmhgfrfe-stack-AWSEBSecurityGroup-1D5BSG71QUTBX 2019-11-04 11:55:06 INFO Created Auto Scaling launch configuration named: awseb-e-yrxmhgfrfe-stack-AWSEBAutoScalingLaunchConfiguration-117EXRROI4681 2019-11-04 11:56:10 INFO Created Auto Scaling group named: awseb-e-yrxmhgfrfe-stack-AWSEBAutoScalingGroup-GFXMDJHNG2WI 2019-11-04 11:56:11 INFO Waiting for EC2 instances to launch. This may take a few minutes. 2019-11-04 11:56:11 INFO Created Auto Scaling group policy named: arn:aws:autoscaling:us-west-2:607492160452:scalingPolicy:bcdf6ff5-32b9-4b0a-9aba-274fbedbba1a:autoScalingGroupName/awseb-e-yrxmhgfrfe-stack-AWSEBAutoScalingGroup-GFXMDJHNG2WI:policyName/awseb-e-yrxmhgfrfe-stack-AWSEBAutoScalingScaleDownPolicy-LOVVFGQVBP2Z 2019-11-04 11:56:11 INFO Created Auto Scaling group policy named: arn:aws:autoscaling:us-west-2:607492160452:scalingPolicy:9fbbafea-cca9-4279-84fb-faec4f0cc934:autoScalingGroupName/awseb-e-yrxmhgfrfe-stack-AWSEBAutoScalingGroup-GFXMDJHNG2WI:policyName/awseb-e-yrxmhgfrfe-stack-AWSEBAutoScalingScaleUpPolicy-1WYK2Q8WDWHDT 2019-11-04 11:56:11 INFO Created CloudWatch alarm named: awseb-e-yrxmhgfrfe-stack-AWSEBCloudwatchAlarmLow-T33T5Y5CO17U 2019-11-04 11:56:11 INFO Created CloudWatch alarm named: awseb-e-yrxmhgfrfe-stack-AWSEBCloudwatchAlarmHigh-1D20PAP6VBZGH 2019-11-04 11:56:42 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2019-11-04 11:56:45 ERROR [Instance: i-0985fbc7c7272a213] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log … -
Where to even begin investigating issue causing database crash: remaining connection slots are reserved for non-replication superuser connections
Occasionally our Postgres database crashes and it can only be solved by restarting the server. We have tried incrementing the max connections and Django's CONN_MAX_AGE. Also, I am trying to learn how to set up PgBouncer. However, I am convinced the underlying issue must be something else which is fixable. I am trying to find what that issue is. The problem is I wouldn't know where or what to begin to look at. Here are some pieces of information: The errors are always OperationalError: FATAL: remaining connection slots are reserved for non-replication superuser connections and OperationalError: could not write to hash-join temporary file: No space left on device. I think this is caused by opening too many database connections, but I have never managed to catch this going down live so that I could inspect pg_stat_activity and see what actual connections were active. Looking at the error log, the same URL shows up for the most part. I've checked the nginx log and it's listed in many different lines, meaning the request is being made multiple times at once rather than Django logging the same error multiple times. All these requests are responded with 499 Client Closed Request. In addition … -
How do I make Open CV work on deployed web app
I have an application that I can run locally and have it open my web camera then detect a qr code. It works well when I run the app locally but then I used the app on my web server and it gets a Server Error (500). The app was made on Django, then for deployment I used digital ocean(ubuntu) and I also use nginx and gunicorn. html <li style= "margin: auto; width:auto"><a style="color:white" href="{% url 'attendees:qrscanner' %}" target="_blank"><button style="margin:15px; width:200px" class="btn btn-outline-primary">Check QR Scanner</button></a></li> views.py from django.shortcuts import get_object_or_404, render, redirect from django.utils import timezone from django.db.models import Sum from .models import Attendee, ActivityLog import re, qrcode, cv2, csv, io, os import numpy as np import pyzbar.pyzbar as pyzbar def qrscanner(request): cap = cv2.VideoCapture(0) font = cv2.FONT_HERSHEY_PLAIN frame_width = int(cap.get(3)) frame_height = int(cap.get(4)) aid = None while aid is None: _, frame = cap.read() decodedObjects = pyzbar.decode(frame) for obj in decodedObjects: aid = re.findall('/attendees/confirmation/([0-9]+)', str(obj.data)) try: attendee = Attendee.objects.get(pk=str(aid[0])) attendee.present = True attendee.timestamp = timezone.now() attendee.activity.update_or_create(time_log=attendee.timestamp) attendee.save() context = { 'scan': 'QR Successfully Scanned', 'attendee': attendee, } except: context = { 'noscan': 'QR Scan Unsuccessful' } cv2.imshow("QR Reader", frame) if aid is not None: cv2.destroyAllWindows() break key = cv2.waitKey(1) … -
Cannot install "psycopg2" on Windows 10
Yesterday I uninstalled python 3.7 version by mistake. Then I install python again (this time 3.8 version) and again set up my environment. But I could not start my Django project which has Postgres connection. Actually I cannot install "psycopg2" in my environment. I searched for hours and implement every solutions I get from online but it does not work. Let me tell you what I did so far. First it said to add Postgres in my PATH so I added C:\Program Files\PostgreSQL\12\bin\ in my PATH. A new problem then arise with a huge ERROR report with 2 vital Error. ERROR: Failed building wheel for psycopg2 .......................... Running setup.py install for psycopg2 ... error I try to upgrade wheel but it says, Requirement already up-to-date http://initd.org/psycopg/docs/install.html#install-from-source I learned from this site that psycopg2 requires python2 version. So I installed python 2.7 also. I reinstalled PostgreSQL but it does not work. I deleted my virtual environment and create again but it does not work. Some says they solve this problem by running pip install psycopg2-binary But it does not work for me. Please help me to get rid of this. I stuck for hours. -
Dealing with multiple databases in Django with and without timezones
I'm in the situation where I use django (2.0.7) to deal with multiples databases: database_A: without timezone; database_B: with timezone 'Europe/Paris'; settings.py USE_TZ = True TIME_ZONE = 'Europe/Paris' DATABASES = { 'database_A': { 'NAME': ... 'PASSWORD': ... etc. 'TIME_ZONE': None, # still raise RuntimeWarning; received a naive datetime while time zone support is active. }, 'database_B': { 'NAME': ..., etc. } on models of database A class Something(models.Model): date_creation = models.DateTimeField() def save(self, *args, **kwargs): if self._state.adding is True: self.date_creation = timezone.datetime.now() # naive print("BEFORE SAVE") print(self.date_creation) super(Something, self).save(*args, **kwargs) print("AFTER SAVE") print(self.date_creation) print("AFTER REFRESH") self.refresh_from_db() print(self.date_creation) I get the following result BEFORE SAVE 2019-11-04 11:44:35.233876 AFTER SAVE 2019-11-04 11:44:35.233929 AFTER REFRESH 2019-11-04 10:44:35.23392 # 10:44:35 , what's wrong ô_O ? I have the same 1 hour difference between Europe/Paris and UTC. import pytz from datetime import datetime datetime.now(tz=pytz.timezone('Europe/Paris')), timezone.now() (datetime.datetime(2019, 11, 4, 12, 10, 55, 320028, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>), datetime.datetime(2019, 11, 4, 11, 10, 55, 320077, tzinfo=<UTC>)) So, I think PostgreSQL is using UTC to save my naive datetime considered as timezone aware datetime ? In database I have the following time \d something_table date_creation | timestamp without time zone | non NULL Par defaut, now() SELECT NOW(); … -
Is there any simplest way to run number of python request asynchronously?
There is an API localhost:8000/api/postdatetime/, which is responsible for changing the online status of the driver. Every time a driver hits the API and if the response sent back then the driver status will be online otherwise the driver status will be offline. Drivers need to give the response within every 10 seconds. If there is no response from the driver then he/she will be marked as offline automatically. Currently what I am doing is getting all the logged in drivers and hitting the above-mentioned API one driver at a time. For the simulation purpose, I populated thousands of drivers. To maintain the online-offline of thousands of drivers using my approach will leave almost many drivers offline. The code for my approach is as described below: online-offline.py import requests import random import math from rest_framework.authtoken.models import Token from ** import get_logged_in_driver_ids from ** import Driver def post_date_time(): url = 'localhost:8000/api/postdatetime/' while True: # getting all logged in driver ids logged_in_driver_ids = get_logged_in_driver_ids() # filtering the driver who are logged in and storing their user id in the driver_query variable driver_query = Driver.objects.only('id', 'user_id').filter(id__in=logged_in_driver_ids).values('user_id') # storing the user id of driver in list driver_user_ids = [driver['user_id'] for driver in driver_query] # … -
Azure Functions Django ModuleNotFoundError
I have been trying to run Django on Azure Function as mentioned in the tutorial below Running serverless Django apps with Functions I am trying to use the following module as mentioned https://github.com/carltongibson/azure-functions-wsgi-adapter The library above does not look maintained, still, the approach is simple enough and should work. I am able to get the code in the tutorial running, but my code is not working. The only difference I see is in the directory stucture(my code and Django by default has one more level in the directory structure). My directory structure is: Running the above gives me the following error on Azure: Exception: ModuleNotFoundError: No module named 'notifications' Stack: File "/azure-functions-host/workers/python/3.6/LINUX/X64/azure_functions_worker/dispatcher.py", line 242, in _handle__function_load_request func_request.metadata.entry_point) File "/azure-functions-host/workers/python/3.6/LINUX/X64/azure_functions_worker/loader.py", line 66, in load_function mod = importlib.import_module(fullmodname) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/site/wwwroot/serverless/__init__.py", line 14, in <module> from notifications.notifications.wsgi import application By default Django project parent directory does not have an __init__.py, I have added it so that import works. Not able to figure out the missing piece here! -
How to use class based views with more than one model?
I am using class based view with a created model, but I am not able to insert another model. models.py: class Test(models.Model): name = models.CharField(max_length=255, null=False, data = models.DateField(null=False, default=date.today) class Test2(models.Model): teste = models.ForeignKey(Test, on_delete=models.CASCADE), data = models.DateField(null=False, default=date.today) views.py without the "Test2" model: class IndexTemplateView(TemplateView): template_name = "index.html" class TestCreateView(CreateView): template_name = "cadastro.html" model = Test form_class = InserePropriedadeForm success_url = reverse_lazy("test:list_test") class TestListView(ListView): template_name = "list.html" model = Test context_object_name = "tests" class TestDetailView(DetailView): template_name = "detail.html" model = Test fields = '__all__' context_object_name = 'test' ... How can I add the model "Test2" to this view? -
Django + JQuery - Iterate over table rows updating each row with json data
I have table rows that look like this {% for item in items %} <tr id="labels" data-index="{{ forloop.counter }}"> </tr> {% endfor %} I have this json data: "labels": [ "A", "B", "C ", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ], Im trying to iterate over the table rows and the json data at the same time, so that I can assign each table row its label. jQuery.each(labels, function() { newlabel = this; document.querySelectorAll('#labels').forEach(function (element, index) { element.innerHTML = newlabel; }); })}, But with this all the rows are populated with the letter Z, instead of being A-Z in alphabetical order. Thank you for any help -
Accessing ForeignKey field value inside template
I have two models Fleet and Ship, Ships are ForeignKey fields of Fleets: class Fleet(models.Model): fleet_ship_n_01 = models.ForeignKey(Ship, on_delete=models.CASCADE, null=True, related_name='fleet_ship_n_01', blank=True) fleet_ship_n_02 = models.ForeignKey(Ship, on_delete=models.CASCADE, null=True, related_name='fleet_ship_n_02', blank=True) fleet_ship_n_03 = models.ForeignKey(Ship, on_delete=models.CASCADE, null=True, related_name='fleet_ship_n_03', blank=True) Ships itself also have many fields like: class Ship(models.Model): ship_class = models.CharField(default='NoClass', max_length=200, help_text="Ship class") ship_tech_level = models.CharField(default=5, max_length=100, choices=tech_level) ship_mass = models.PositiveIntegerField(default=0, help_text="Ship mass") I have an update view in which i am adding ships to Fleet: class UVFleetDetails(UpdateView): template_name = 'fading_thrust/fleet_details_form.html' model = Fleet form = FleetForm() total_ship_mass = 0 fields = ('fleet_ship_n_01', 'fleet_ship_n_02', 'fleet_ship_n_03', 'fleet_ship_n_04', 'fleet_ship_n_05', 'fleet_ship_n_06', 'fleet_ship_n_07', 'fleet_ship_n_08', 'fleet_ship_n_09', 'fleet_ship_n_10', ) def form_valid(self, form): fleet = form.save() fleet_id = self.kwargs['pk'] fleet.fleet_id = fleet_id fleet.save() return redirect('fleet_details', pk=fleet_id) here is its form: class FleetForm(ModelForm): fleet_ship_n_1 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_2 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_3 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_4 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_5 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_6 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_7 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_8 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_9 = forms.ModelChoiceField(Ship.objects.all(), required=False) fleet_ship_n_10 = forms.ModelChoiceField(Ship.objects.all(), required=False) class Meta: model = Fleet fields = ('fleet_ship_n_01', 'fleet_ship_n_02', 'fleet_ship_n_03', 'fleet_ship_n_04', 'fleet_ship_n_05', 'fleet_ship_n_06', 'fleet_ship_n_07', 'fleet_ship_n_08', 'fleet_ship_n_09', 'fleet_ship_n_10',) Now when adding ships to a Fleet i want to display also important details about those ships. Like ship_class, ship_tech_level, … -
Django-based Quiz app: Answers and Answer Verification
I am creating a Django-based quiz application(MCQ type) in which i have reached the stage where my questions with options(answers) with checkboxes are being displayed but i required help on how to proceed forward from here.I needed help to take the input from the user after he/she selects the checkboxes and clicks on 'submit' button and to verify whether the answers are correct. Here is my html file/code- {% extends "app/basic_app_base.html" %} {% block body_block %} <h1>{{ question.question_text }}</h1> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <ol> {% for question in questions %} <form action="{% url 'app:detail' question.id %}" method="post"> {% csrf_token %} <h3>{{ question.question_text }}</h3> {% for choice in question.choice_set.all %} <input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }} </label> {% endfor %} <br> {% endfor %} </ol> <input type="submit" name="" value="Submit"> </form> </body> {% endblock %} I am looking for the code after this step.Please help. -
How to access the user details when i use the original user model as a foreign key in Django
I have a book model as below : from django.db import models from django.db.models.signals import pre_save from django.utils.text import slugify from django.conf import settings class Book(models.Model): added_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, related_name='book_add', on_delete=models.CASCADE), last_edited_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, related_name='book_edit', on_delete=models.CASCADE) title = models.CharField(max_length=120) description = models.TextField(null=True, blank=True) slug = models.SlugField() updated = models.DateTimeField(auto_now_add=False, auto_now=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) @property def user_id(self): return self.added_by.id def __str__(self): return self.title def pre_save_book(sender, instance, *args, **kwargs): slug = slugify(instance.title) instance.slug = slug pre_save.connect(pre_save_book, sender=Book) Now in my admin.py file i am trying to do this : from django.contrib import admin from .models import Book from .forms import BookForm class BookAdmin(admin.ModelAdmin): fields = [ 'title', 'slug', 'added_by' ] read_only_fields = [ 'updated' 'timestamp', 'added_by', 'last_edited_by' ] admin.site.register(Book, BookAdmin) I am getting an error which says the added_by field is not recognized , but it should be right, since i have defined it as a foreign key on the original user model. So i tried to go to the console and try it out : (Django-concepts) ~/Desktop/Studies/Codes/Django-concepts/django_cls_views:$ python manage.py shell Python 3.7.3 (default, Mar 27 2019, 09:23:15) [Clang 10.0.1 (clang-1001.0.46.3)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from …