Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ? -
How to set option additional option to map in django-leaflet
I need to set an option {editable: true} at the moment i create map object like this: var map = L.map('map', {editable: true}); But i'm using django-leaflet extension where i just subscribe on callback and get already created map object: {% leaflet_map "map_frame" callback="window.show_layers" %} function display_layers(map, options){ ... } May be it possible that i somehow pass this option to template tag or some other way to activate leaflet Editable plugin. https://github.com/Leaflet/Leaflet.Editable -
CSRF and CORS with Django (REST Framework)
We're in the process of moving our frontend into a separate project (out of Django). It's a Javascript single page application. One of the reasons is to make it easier for our frontend developers to do their work, not having to run the entire project -- including the API -- locally. Instead, we'd like them to be able to communicate with a test API we've set up. We've managed to solve most of the CORS/CSRF issues along the way. But now we've run into something I can't find a solution for anywhere, despite reading lots of documentation and SO answers. The frontend and the API are served from different domains (during development localhost and test-api.example.com). Until now, while served from the same domain, the frontend has been able to get the CSRF token from the csrftoken cookie set by the API (Django). But when served from different domains, the frontend (localhost) can't access the cookies of the API (api-test.example.com). I'm trying to figure out a way to work around this, to somehow deliver the CSRF token to the frontend. The Django docs recommend to set a custom X-CSRFToken header for AJAX requests. Would we compromise the CSRF protection if we … -
Should I use groups in live chat made with Django Channels 2?
I am trying to create a live chat for a website where the admin can chat with everyone individually from the backend. But users can only chat with the admin, not with each other. I was reading up on the docs for channels and I read: Anyone who has the name of a channel can send a message to the channel. So do I need to create a group for each user with that user and the admin in that group for them to chat? Or can I just use the channel name from the consumer instance and use that somehow for the admin to chat with the user? -
application of simple choice task in django
I have just finished the django tutorial here https://docs.djangoproject.com/en/2.0/intro/tutorial01/. But I am still not sure to write the following intended application. The application asks an user to enter his/her name, then to make 30 choices. At the end I need to record those choices under the user's name. The major part I am confusing is about data export and import. The tutorial shows how to enter the questions in a shell. But I would like to the program to read parameters from a matlab matrix(say 30*10 matrix), or whatever files possible. Here the number of rows is equal to 30, which is equal to the number of task. Essentially I only need one form. The form should literately read one row from the matrix hence shows a parameterised choice task to the user. The user makes a choice and proceeds to next form. The next form will read the next row from the matrix and shows a new choice task. I suspect for a simple application like this I may not even need to create a database. Just create a list and export it will do the work. Is any one can let me know where to find an example/ … -
Django how to check if objects contains string in multiple fields
So I have a model called Puzzle which contains a title, question, and a subject. I want to be able to search for puzzles by entering a string. My search bar also contains three checkboxes: - title - question - subject I want to somehow be able to query my database to see if the ticked fields contain the search text. For example, if title and question were ticked, I would query to see if the puzzle's title contains this string OR its questions contains the string. Is there any way to query this in Django? I know that if I wanted to check just one of these fields, for instance the title, I could just do this: Puzzle.objects.filter(title__contains=search_text) But I want to be able to dynamically query the fields that are ticked. Currently, my view contains three boolean values: title, question, and subject. The boolean is True is it is ticked, and false if it is not ticked. How can I manipulate these three booleans along with Django queries to be able to dynamically query my database? Thank you -
Django foreignkey
I am trying to add new patient details to the following piece of code and linking to mysql database as i have created in the settings.. I am getting an error OperationalError at / (1054, "Unknown column 'patCube_patientlist.no_id' in 'field list'")but i never created such a column. why did this happen.. models.py from django.db import models from django.utils import timezone class PatientList(models.Model): no = models.ForeignKey('auth.User', on_delete=models.CASCADE) patientID = models.CharField(primary_key = True,max_length=200) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) address = models.CharField(max_length=200) age = models.IntegerField(max_length=200) ssn = models.CharField(max_length=200) added_date = models.DateTimeField( default=timezone.now) created_date = models.DateTimeField( blank=True, null=True) def create(self): self.published_date = timezone.now() self.save() def __str__(self): return self.patienID views.py from django.shortcuts import render from .models import PatientList from django.utils import timezone def plist(request): patient = PatientList.objects.filter(created_date__lte=timezone.now()).order_by('created_date') return render(request, 'patCube/plist.html', {'patient': patient}) def patient_detail(request, pk): pat = get_object_or_404(Post, pk=pk) return render(request, 'patCube/patientdetail.html', {'pat': pat}) def add_patient(request): if request.method == "POST": form = PatientForm(request.POST) if form.is_valid(): newpatient = form.save(commit=False) newpatient.no = request.user newpatient.created_date = timezone.now() newpatient.save() return redirect('patient_detail', pk=newpatient.pk) else: form = PatientForm() return render(request, 'patCube/add_patient.html', {'form': form}) plist.html {% extends 'patCube/base.html' %} {% block content %} {%for pat in patient%} <div class="patient"> <div class="date">{{ pat.created_date }}</div> <h1><a href="{% url 'patient_detail' pk=pat.pk %}">{{ pat.patientID }}</a></h1> … -
Django Error While Submitting Forms
Performing system checks... Unhandled exception in thread started by .wrapper at 0x75abfcd8> Traceback (most recent call last): File "/home/pi/.venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/pi/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/home/pi/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "/home/pi/.venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/pi/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "/home/pi/.venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/home/pi/.venv/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 958, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 673, in exec_module File "", line 222, in _call_with_frames_removed File "/home/pi/tango_with_django_project/tango_with_django_project/urls.py", line 25, in url(r'^rango/', include('rango.urls')), File "/home/pi/.venv/lib/python3.5/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/home/pi/.venv/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in …