Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass values into python script from django views
When a user logins in, they provide a username, password, serverid. I want to pass that into a script that would connect them to a server. How do I do so and also get the output of the script to see if it was executed properly? -
Django use queryset in template
I want to check a field(=is_seller) of the table(=UserProfileInfo) and if it has some value(=0) , make some part of template disabled and these are my codes : models.py : class UserProfileInfo(models.Model): user=models.OneToOneField(User,related_name='profile') companyname=models.CharField(blank=True,null=True,max_length=128,verbose_name=_('companyname')) phone_regex = RegexValidator(regex=r'^\d{11,11}$', message=_(u"Phone number must be 11 digit.")) cellphone = models.CharField(validators=[phone_regex], max_length=17,verbose_name=_('cellphone')) tel = models.CharField(blank=True,null=True, max_length=17,verbose_name=_('tel')) state=models.CharField(,max_length=128,verbose_name=_('state')) city=models.CharField(,max_length=128,verbose_name=_('city')) address=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('address')) is_seller=models.CharField(blank=True,null=True, max_length=2,verbose_name=_('seller')) def __str__ (self): return self.user.username class Meta: verbose_name=_('UserProfileInfo') verbose_name_plural=_('UserProfileInfos') view.py: def stock(request): st_form=StocksForm(None) is_seller=UserProfileInfo.objects.filter(user=request.user).values("is_seller") if request.method == "POST": st_form =StocksForm(data=request.POST) print("<<<<<<<<<<<"+str(is_seller)) if st_form.is_valid(): instance=st_form.save() id_name=(st_form.cleaned_data.get("name")) instance.name=StocksName.objects.filter(id=id_name).values("name")[0]['name'] #becouse of autocomplete it was saving the value by its id and i converted to name instance.user=request.user instance.save() messages.success(request,"SUCCESSFUL" ,extra_tags="savestock") else: messages.error(request, "ERROR!") else: st_form=StocksForm() return render(request,'BallbearingSite/stock.html',{'stocks_form':st_form,'seller':is_seller}) template.html : it doesnt work and i dont know how to correct it : {% for item in seller %} {% if item.is_seller=="0" %} <p>show some message</p> {% endif %} {% endfor %} -
Pass from login a variable to know is the first time the user login
First time the use logins, I wan to show him a multi step setup. How can I pass from login a variable to know is the first time the user login ? -
What is better for an embedded device - Node.js or Django?
Background: I'm currently developing a project on Raspberry Pi - for now I want to gather data from a sensor and display it on a web page with some neat graphs and stuff like that but I plan to expand it sooner or later. I'm facing a dilemma right now: which framework should I use? I learned about Node.js from this book and I really like the concept - also the authors are giving quite a few reasons why it's good for embedded devices. On the other hand, I learned about the existence of Django and since I'm working with python on a daily basis I thought using it would be a better idea. I'm torn apart now - I'd like to use technology that would be most suitable in embedded world (and which would educate me the most) and yet I'm kinda afraid to jump into deep waters of a language I don't really know (JavaScript). If somebody with more experience with web technology and embedded devices could help me out, that would be most helpful! In short: What would be the best option for an embedded device (and for me): Node.js or Django? -
How do I handle files stored as blob from react-dropzone
When I add files to the file field using react-dropzone and pass it to a remote Django backend, it passes the values: {u'preview': u'blob:http://127.0.0.1:8080/17c3c181-e361-44f1-8ee8 -6476847aeffb'} . How do I handle that as a file for uploading to S3 using a Django Rest API backend? -
Can't Access the file from path Aws + Django
I am using Django-mailbox, an AWS-EC2 instance and AWS-S3 , I am trying to send an attachment with mail and receive it on S3 bucket and I am successful to achieve this. Now while accessing that attachment file from path, it is shows me following error, how file is saved successfully in given path My folder structure is as follows Let me know if any further details needed. -
Django Redirect Solution
In django I am having problems redirecting. Here is my urls.py for the app: urlpatterns = [ path('bkb/', views.index, name = 'index'), path('bkb/<int:department_code>/', views.lcdcl, name ='lcdcl'), path('bkb/<int:department_code>/<int:cl_id>/', views.lcdcl2, name ='lcdcl2'), path('bkb/addcl2/' , views.addcl2, name='addcl2'), path('bkb/<int:department_code>/<int:cl_id>/<int:edit_id>/edit/', views.editdata, name ='editdata'), path('bkb/<int:dept_code>/<int: id>/revers/', views.revers, name ='revers'), here is my view.py for edit data: def editdata(request, department_code, cl_id, edit_id): editdata = CL2.objects.get(pk=edit_id) cl2_info = LCD.objects.get(pk=cl_id) a = department_code b = cl_id if request.method == "POST": forms = CL2Form(request.POST, instance=editdata) if forms.is_valid(): editdata = forms.save(commit=False) editdata.save() return redirect('/bkb/lcdcl2/') else: forms = CL2Form(instance=editdata) context = {'forms' : forms} return render(request, 'bkb/lcdcl2form.html', context) My question is: I want to go to path('bkb/<int:department_code>/<int:cl_id>/', views.lcdcl2, name ='lcdcl2'), from return redirect('/bkb/lcdcl2/') in views. -
getting image source using beautiful soup
here is my code but in this i get source of first product scrap = requests.get('https://www.walmart.com/search/?query=s5&cat_id=0') content = BeautifulSoup(scrap.text, "html.parser") categories = content.findAll("div", {"class": "search-result-gridview-item-wrapper"}) for category in categories: name = category.find("div", {"class": "search-result-product-title gridview"}) title = name.find('a').text price = category.find("div", {"class": "search-result-productprice gridview enable-2price-2"}) p = price.text k=category.find("div",{"class":"search-result-gridview-item clearfix"}) image=k.find("div",{"class":"display-inline-block pull-left prod-ProductCard--Image"}) img = image.a.find("img", {"class": "Tile-img"})['src'] print (img) href=image.find('a')['href'] product_href.append(href) image_source.append(img) product_name.append(title) product_price.append(p) output of print(img) //i5.walmartimages.com/asr/76f06b1a-b180-43dd-91a7-566de4c1be6c_1.4d16dafe13a43abb89aaeab9927d4152.jpeg?odnWidth=180&odnHeight=180&odnBg=ffffff //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif //i5.walmartimages.com/dfw/63fd9f59-33e4/k2-_1255bd77-c218-4f2a-99ce-14731eeaa110.v1.gif -
Django Dynamic Form Filter
I'm creating a web based ERP-like system in Django 2.0. In a page, I have a form with all the Work Orders or so entries (stored in DB). I would like to have in the first line of the form (below the headers) a input field for each column where I type and it dynamically/instantly filter the form rows. Example: COD | DESCRIPTION | DATE | ETC. search field | search field | search field | search field So when I type any character in any column, instantly the form is updated showing the filter results. Which technique I should use for this? Is Ajax the tool for this job? -
Creating an REST API Django
First thing that I would like to say is that I have no previous experience with python and any framework python related. However, I have programming experience. So, I want to create an REST API using pythona with frameworks djnago and djangorestframework. I have managed to create the database (using postgresql) and also managed to to create the initial migration. However, I believe that that was the easiest part and I have some questions about the thing that I'm about to implement: First I want to create an authentication system. I saw that djangorestframework it's able to manage authentication by itself but I was not able to make it run. Can you please guid me to some good tutorials/provide code samples and briefly explain? After initial migration I saw that django created some tables for authentication and session management by itself (auth_user, auth_user_groups, etc). Is there any way to use my own model for user? Also, i do believe that I wont need all the features that django offerrs (e.g auth_user_groups). Its there any way to remove those unwanted functionalities? I was able to create an API endpoint (by following a tutorial) that returns some data (based on a model, … -
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> django project
gunicorn status gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor Active: failed (Result: exit-code) since Mon 2018-03-12 18:30:15 UTC; Process: 3535 ExecStart=/home/mike/movingcollage/movingcollageenv/bin/ Main PID: 3535 (code=exited, status=1/FAILURE) Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: File "/home/mike/mo Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: time.sleep(0.1) Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: File "/home/mike/mo Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: self.reap_workers Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: File "/home/mike/mo Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: raise HaltServer( Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: gunicorn.errors.HaltS Mar 12 18:30:15 ubuntu-2gb-nyc3-01 systemd[1]: gunicorn.service: Main pr Mar 12 18:30:15 ubuntu-2gb-nyc3-01 systemd[1]: gunicorn.service: Unit en Mar 12 18:30:15 ubuntu-2gb-nyc3-01 systemd[1]: gunicorn.service: Failed 29 ubuntu-2gb-nyc3-01 systemd[1]: gunicorn.service: Failed nginx error log: 2018/03/12 04:59:08 [error] 1562#1562: *1787 connect() to unix:/home/mik e/movingcollage/movingcollage.sock failed (111: Connection refused) whil e connecting to upstream, client: 107.205.110.154, server: movingcollage .com, request: "GET / HTTP/1.1", upstream: "http://unix:/home/mike/movin gcollage/movingcollage.sock:/", host: "movingcollage.com" My config is ok, this used to work; I pulled some new application code and am now getting a 502 bad gateway error (before I pulled the application code the site worked fine). I already did service gunicorn restart and systemctl restart gunicorn and am still getting the 502 bad gateway error. Can anyone help? This is a django project, for what it's … -
Wagtail 2.0 installation error
When I install a fresh copy of wagtail 2.0, the requirements file still wants to call for wagtail 1.14. I change that to 2.0 and django to 2.0, rerun the import and I get this error: Traceback (most recent call last): File "./manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/Users/johnbriggs/.virtualenvs/wagtail/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/johnbriggs/.virtualenvs/wagtail/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Users/johnbriggs/.virtualenvs/wagtail/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/johnbriggs/.virtualenvs/wagtail/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/Users/johnbriggs/.virtualenvs/wagtail/lib/python3.6/site-packages/django/apps/config.py", line 123, in create import_module(entry) File "/Users/johnbriggs/.virtualenvs/wagtail/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'wagtail.wagtailforms' Here is my updated requirements.txt file: Django>=2.03 wagtail>=2.0 I can run these fine, but everything bugs at at the migrate process. -
Channels Websocket immedialty disconnecting with ssl
I tried to make run the tutorial from the channels docs on my production server, using ssl. After a few hours i managed to get a connection but it instantly disconnects : None - - [12/Mar/2018:17:42:22] "WSCONNECTING /ws/chat/bibou/" - - None - - [12/Mar/2018:17:42:22] "WSCONNECT /ws/chat/bibou/" - - None - - [12/Mar/2018:17:42:23] "WSDISCONNECT /ws/chat/bibou/" - - my stack is ubuntu 16.04 nginx 1.10.3 channels==2.0.2 daphne==2.1.0 channels-redis==2.1.0 Twisted==17.9.0 I have the exact copy paste of the code from the tutorial, except for this part in room.html var chatSocket = new WebSocket( 'wss://' + window.location.host + ':8443/ws/chat/' + roomName + '/'); and here is my nginx conf server { #http listen 80; server_name groover.co; root /usr/share/nginx/html; include /etc/nginx/default.d/*.conf; location / { return 301 https://$server_name$request_uri; } } server { #https listen 443 ssl; listen 8443 ssl; server_name groover.co; root /usr/share/nginx/html; ssl_certificate "/etc/letsencrypt/live/groover.co/fullchain.pem"; ssl_certificate_key "/etc/letsencrypt/live/groover.co/privkey.pem"; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; add_header Strict-Transport-Security "max-age=31536000"; include /etc/nginx/default.d/*.conf; location /static/ { root /home/ubuntu; } location /media/ { root /home/ubuntu; } location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://unix:/home/ubuntu/tlebrize/Groover.sock; } location /ws/ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header … -
How to display python dictionary in a Django template in bullet list format?
How do I alter the following Django template code: <ul> {% for key, value in real_prices.items %} #real_prices is a dictionary <li>Price: {{ key }}, link: {{value}}</li> {% endfor %} </ul> To display the dictionary items on a page like this: Price: key, link: value Price: key, link: value Price: key, link: value and so on... The current code only displays the dictionary as a whole. For reference, here's the view: def test(request): prices = [] real_prices = [] links = [] url = 'https://www.airbnb.pl/s/Girona--Hiszpania/homes?refinement_paths%5B%5D=%2Fhomes&query=Girona%2C%20Hiszpania&place_id=ChIJRRrTHsPNuhIRQMqjIeD6AAM&checkin=2018-04-04&checkout=2018-04-22&children=0&infants=0&adults=2&guests=2&allow_override%5B%5D=&price_max=252&room_types%5B%5D=Entire%20home%2Fapt&min_beds=0&s_tag=Ph6ohhjw' response = requests.get(url) soup = bs4.BeautifulSoup(response.text) #prices page_selectors = soup.select('._1bdke5s') print(len(page_selectors)) last_page_selector = page_selectors[len(page_selectors) - 4]##############-15 last_page_selector = last_page_selector.getText() for x in range(0, int(last_page_selector)): response = requests.get(url + '&section_offset=' + str(x)) response_text = response.text soup = bs4.BeautifulSoup(response_text) spans = soup.select('._hylizj6 span') for i in range(0, len(spans)): prices.append(spans[i].getText()) for price in prices: if 'zł' in price: real_prices.append(price) #links a_tags = soup.find_all('a') for tag in a_tags: if '_15ns6vh' in str(tag.get('class')): link = 'https://www.airbnb.pl' + str(tag.get('href')) links.append(link) dictionary = dict(zip(real_prices, links)) -
How to implement phonetic typing for Indian languages in django-ckeditor
I have integrated CKeditor in my application with the help of django-ckeditor package. I want to add support for phonetic typing in English and transliterating the words in Indian Language (such as Hindi), very similar to what quillpad does. Any hint/help to achieve the desired result will be highly appreciated. -
Create a session in Django Rest Framework
I have a Django Rest Framework API that authenticates through Firebase. On the frontend after the user has logged in with Firebase, a token is sent to the backend that is verified, Firebase returns a user_id after verification and this is used to return the current user. I have written a simple custom authentication class that handles the token verification. The token is set as tokenid header. Here's the code: from rest_framework.authentication import BaseAuthentication from rest_framework import exceptions import firebase_admin from firebase_admin import credentials, auth from .models import User CREDS_PATH = 'PATH_TO_CREDS.json' cred = credentials.Certificate(CREDS_PATH) default_app = firebase_admin.initialize_app(cred) class FirebaseAuthentication(BaseAuthentication): """Authenticate the user and get its info from Firebase. The token is sent in the request as idToken and veryfied with the Firebase admin. """ def authenticate(self, request): """Actual authentication happens here.""" token = request.META.get('HTTP_TOKENID') if token: try: firebase_user = auth.verify_id_token(token) except ValueError: return None if not firebase_user: return None user_id = firebase_user.get('user_id') try: user = User.objects.get(id=user_id) print(user) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) else: # no token provided return None Then I create a View that is connected to /login route and that uses FirebaseAuthentication and SessionAuthentication. The idea is for this endpoint to verify the … -
django username "disappears" when going in another view
Before I start, I'd like to point out that I have already surfed half of the internet in search of a possible solution, but nothing really solved my problem. That said, I'm quite the beginner in Django and Python so this could be a simple problem and maybe I'm just too dumb to figure it out. So, here's the thing. I'm working on a project for college and I have to make a website that emphasises primarily backend. I chose Django as a framework and so far I've been able to have new users register and also log in and out. The problem is maybe not dramatic, but annoying for me at least. To be more clear, After a user logs in, I want to show his name in the top bar alongside the logout button. So, the log in panel is as such: This part is fine, I just hit Log In and it works. Then I get here: As you can see, at first, the username is displayed in the top bar alongside the logout. But if I click on "Whatever" or the username itself, it goes away. This may have something to do with the fact that … -
Elastic Search not Indexing
When trying to index new users in out Django app, Elastic is unable to index...returning a key error of key ['created'] Traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home//venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/app/management/commands/index_users.py", line 19, in handle bulk_indexing(User) File "/home/uapp/management/commands/index_users.py", line 12, in bulk_indexing bulk(client=es, actions=(m.indexing() for m in model.objects.all())) File "/home/venv/local/lib/python2.7/site-packages/elasticsearch/helpers/__init__.py", line 257, in bulk for ok, item in streaming_bulk(client, actions, **kwargs): File "/home//venv/local/lib/python2.7/site-packages/elasticsearch/helpers/__init__.py", line 180, in streaming_bulk client.transport.serializer): File "/home/venv/local/lib/python2.7/site-packages/elasticsearch/helpers/__init__.py", line 58, in _chunk_actions for action, data in actions: File "/home/app/management/commands/index_users.py", line 12, in <genexpr> bulk(client=es, actions=(m.indexing() for m in model.objects.all().iterator())) File "/home/app/models.py", line 137, in indexing obj.save(index="users") File "/home/venv/local/lib/python2.7/site-packages/elasticsearch_dsl/document.py", line 418, in save return meta['created'] KeyError: 'created' I believe the iterator I am just unsure as what actually happening. Can provide more code if needed. -
Django combine foreign keys in a single queryset
I have a model in a Django application that is being referenced by multiple other models as a ForeignKey. What I am looking for is for a way to create a single queryset for all objects of this class that are being referenced as ForeignKey by the rest of the classes based on some criteria. I am not even sure if this is possible, but I thought about asking anyway. class Person(models.Model): pass class Book(models.Model): year_published = models.PositiveIntegerField() author = models.ForeignKey(Person) class MusicAlbum(models.Model): year_published = models.PositiveIntegerField() producer = models.ForeignKey(Person) recent_books = Book.objects.filter(year_published__gte=2018) recent_music_albums = MusicAlbum.objects.filter(year_published__gte=2018) # How can I create a **single** queryset of the Person objects that are being referenced as `author` in `recent_books` and as `producer` in `recent_music_albums`? Thanks for your time. -
Allauth Social Login with DRF JWT
I am using DRF, DRF-JWT, Allauth and Res-auth and djangorestframework-jwt-refresh-token in my Django Application. I have a custom JWT Register Serializer to collect some additional user info and create and create a refresh-token that is used to refresh expired JWT tokens. We have that working across backend and ios Application with no problems for email signup. I am now trying to implement the JWT with the sociallogin element of allauth in particular facebook as a provider. I can create a refresh token against a facebook user by overriding the DefaultSocialAccountAdapter but I'm struggling to return a Json response with a JWT with said refresh token to mobile client. This creates refresh token: class CustomSocialAccountAdapter(DefaultSocialAccountAdapter): def save_user(self, request, sociallogin, form): user = super(CustomSocialAccountAdapter, self).save_user(request, sociallogin, form) app = 'users' user.refresh_tokens.create(app=app) return user I can create JWT manually with this: jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) I'm just having difficulty putting it all together, should I be overriding the adapter or using pre_social_login signal. Any pointers appreciated. -
MySQL Test DB Failing
I set up a Django 2 app (and Python 3.6) with a remote MySQL DB (using mysqlclient), with proper permissions. When I run my unit test, I get the following error: django.db.utils.ProgrammingError: (1146, “Table ‘test_<db>.<db>’ doesn’t exist”). Technically I could create a local dev DB for testing, but I would prefer to figure out this error. -
Upgrading to django 1.11 many to many column not found
I'm upgrading a project from Django 1.10.8 to 1.11 and am suddenly getting weird bugs in my unit tests. I've used a slight hack to update an existing many-to-many relation to use a custom 'through' table with an extra 'order' field. All worked fine in 1.10 but now fails in 1.11 with django.db.utils.ProgrammingError: column api_session_pollgroups.pollgroup_id does not exist My model code looks like this: class SessionPollGroup(models.Model): session = models.ForeignKey('api.Session') pollgroup = models.ForeignKey('api.PollGroup') order = models.PositiveSmallIntegerField(default=0) class Meta: db_table = 'api_session_pollgroups' ordering = ('order',) the table 'api_session_pollgroups' was preexisting when the initial many-to-many relation was made and I 'hijacked it' to add the extra order field. relation on the session model looks like this pollgroups = models.ManyToManyField('api.PollGroup', related_name='sessions', through=SessionPollGroup) Anyone know why this would fail to either generate or find the correct db schema in django 1.11 and not 1.10 ? Note: this seems to only appear during unit tests, when i create a new database using regular migrations the tables appear to be created correctly in my development db ( postgres ) but not in the unit test db ( sqlite ) thanks! -
Why do I get redirected to https://www.facebook.com/dialog/return/close#_=_ instead of the main facebook page?
So, I have a project in Django that is supposed to post some stuff on facebook, which apparently it does, but instead of opening the proper page it goes to blank https://www.facebook.com/dialog/return/close#= instead. Very inconvenient for a potential client. -
Django object filtering across multiple models
I have a Django app for articles. Each article can be commented on and articles can be published as a set of articles with an optional pre-face (which can be also commented upon). I allow tagging of articles and pre-faces, tags are hierarchical (eg category Culture covers Theater, Movies etc). Tags can be extracted from pre-faces and articles directly, or from comments. Tags form comments are relevant to the article / pre-face they belong to too. If a pre-face contains a tag, it is relevant for all articles in the set. So if we have a set with a pre-face and two articles, and the pre-face is in the comment tagged as Theater, this tag is relevant for given comment, pre-face and all articles. If article 1 in the set is tagged with a Movies tag, that tag is relevant only for the article itself. Part of models.py, keeping out fields that shouldn't be relevant to question (like headlines, text etc): class TagName(models.Model): value = models.CharField(max_length=255, unique=True) class TagCategory(models.Model): # Allow association with both articles and comments content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() belongs_to = GenericForeignKey('content_type', 'object_id') tags_in_category = models.ManyToManyField(TagName) # Contains eg regex pattern for category extraction category_info … -
About pythonType
I want ask you about Type of value in Django 2.0.2, I have code ======================================== in file with name (models.py) class AutherDetalis(models.Model): author = models.ForeignKey(Author,on_delete=models.PROTECT) post = models.ForeignKey(Post,on_delete=models.PROTECT) def __str__(self): return "{} - {}".format(self.author,self.post) ======================================== in file with name (views.py) class AuthorView(DetailView): model = AutherDetalis template_name = "AuthorView.html" context_object_name = "authorview" slug_field = "author" ======================================== in file with name (urls.py) path('AuthorView/<slug>/',AuthorView.as_view(),name="AuthorView"), when I write " /AuthorView/ " they ValueError comes and he says : invalid literal for int() with base 10: '<name_of_author>' ======================================== I want ask about the value of <name_of_author> What is ? and how I can solve the problem ?