Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Implement 3-way Dependent/Chained Dropdown List with Django?
I am using django and postgresql. I'm dealing with a 3-way dependent drop-down list. After adding the country selection, the province area is automatically updated depending on the selected country. After selecting a province, the county field opens only when the page is refreshed. I would be glad if you help me in this regard. models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class District(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Person(models.Model): name = models.CharField(max_length=100) birthdate = models.DateField(null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) district = models.ForeignKey(District, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name forms.py from django import forms from .models import Person, Country, City, District class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'birthdate', 'country', 'city', 'district') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() if 'country' in self.data: try: country_id = int(self.data.get('country')) self.fields['city'].queryset = City.objects.filter(country_id=country_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['city'].queryset = self.instance.country.city_set.order_by('name') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['district'].queryset = District.objects.none() … -
How to Create and change Dynamic shared and periodic_tasks tasks by api in Django
I'm using Celery to run periodic_tasks and schedule task. @shared_task def first(city): print(city) @celery_app.on_after_finalize.connect def first_periodic_tasks(sender, **kwargs): sender.add_periodic_task( crontab(minute=0, hour=15), job.s('test'), ) @celery_app.task def job(arg): print(arf) I want to create second_periodic_tasks dynamic using my api. AND I also want to change first_periodic_tasks run time using my api. How can i do this using Celery? -
I got this error when installing psycopg2 in Centos7
I'm using pip install psycopg2 but i got this error; Centos7 Collecting psycopg2 Using cached https://files.pythonhosted.org/packages/5c/1c/6997288da181277a0c2 9bc39a5f9143ff20b8c99f2a7d059cfb55163e165/psycopg2-2.8.3.tar.gz Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Complete output from command /var/www/vhosts/sample.com/httpdocs/venv/ bin/python3 -u -c 'import setuptools, tokenize;__file__='"'"'/tmp/pip-install-bi jd4pos/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__ );code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(cod e, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-86gg6c3t --python-t ag cp36: ERROR: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/psycopg2 copying lib/pool.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/errors.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/sql.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_range.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_lru_cache.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/compat.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_ipaddress.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-3.6/psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/psycopg gcc -pthread -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protec tor-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic - D_GNU_SOURCE -fPIC -fwrapv -fPIC -DPSYCOPG_VERSION=2.8.3 (dt dec pq3 ext) -DPG_V ERSION_NUM=90224 -I/usr/include/python3.6m -I. -I/usr/include -I/usr/include/pgs ql/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-3.6/psycopg/psyc opgmodule.o -Wdeclaration-after-statement In file included from psycopg/psycopgmodule.c:27:0: ./psycopg/psycopg.h:34:20: fatal error: Python.h: No such file or directory #include <Python.h> ^ compilation terminated. It appears you are missing some prerequisite to build the … -
Using custom schema in model's db_table
I have several schemas in postgresql. Now all of my django models are in public schema (i always have written db_table in models to manage table names). Now i need to migrate models from public schema (default) to new schema (named workadmin). How can i change postgres schema for my models? Change db_table to db_table = 'workadmin\".\"realty_land_plot' helped for many people, but those messages were for a long time ago. I have tried to use this way, but migrate command gave me the message: django.db.utils.ProgrammingError: ОШИБКА: ошибка синтаксиса (примерное положение: ".") LINE 1: ...TER TABLE "realty_land_plot" RENAME TO "workadmin"."realty_l... it means syntax error at "." symbol during alter table process. db_table = 'realty_land_plot' -
Why page is getting loaded even I use ajax?
I am using ajax to submit the form when I try to submit the form it is showing the error jquery-3.4.1.js:9837 POST http://127.0.0.1:8000/shop/tracker/ 404 (Not Found). I have added event.preventDefault(); still it is not working $.ajax({ type: 'POST', url: '/shop/tracker/', data: formData, encode: true }) .done(function(data) { console.log(data) updates = JSON.parse(data); if (updates.length > 0 & updates != {}) { for (i = 0; i < updates.length; i++) { let text = updates[i]['text']; let time = updates[i]['time']; mystr = <li class="list-group-item d-flex justify-content-between align-items-center"> ${text} <span class="badge badge-primary badge-pill">${time}</span> </li> $('#items').append(mystr); I am expecting the html output in the same page but there is no changes occuring. -
How to encrypt Messages in Django Channels
Well i have gone through the tutorials of django channels. But the is a loop hole since there is no explanation on how to encrypt a message in django channel. Lets say i have a chat models bellow class ChatThread(models.Model): name=models.CharField(null=True,max_length=200) class chat(models.Model): thread_id=models.ForeignKey(ChatThread,null=True) messages=models.TextField() I want the object of chat to be encrypted when created and decrypted on request within the application. Please i am new to python, so be kind with your explanations. Thanks -
No module named 'rest_frameworkoauth2_provider'
I am setting up a django rest api and need to integrate social login feature.I followed the following link Simple Facebook social Login using Django Rest Framework. After setting up all , when a migrate (7 th step :- python manage.py migrate ) , getting the error ' ModuleNotFoundError: No module named 'rest_frameworkoauth2_provider' ' . Is there any package i missed? i cant figure out the error. -
How do I connect Django to a DB2 database on IBM Cloud?
I am trying to create a simple data entry (CRUD) application using Django and DB2 on the Cloud. The question is, how do I actually do that? I started trying to follow this tutorial. It's not on the cloud, but it's specifically what I can found close about Django with DB2. Following my intuition, I created a credential on DB2 via IBM Cloud console and filled settings.py's DATABASES variable with the following: DATABASES = { 'default': { 'ENGINE': 'ibm_db_django', 'NAME': 'BLUDB', 'USER': '*********', 'PASSWORD': '***********', 'HOST':'**********.services.<loc>.bluemix.net', 'PORT': 5000, 'PCONNECT' : True, } } However, after trying to run python manage.py migrate, I got the following error: django.db.utils.Error: [IBM][CLI Driver] SQL1531N The connection failed because the name specified with the DSN connection string keyword could not be found in either the db2dsdriver.cfg configuration file or the db2cli.ini configuration file. Data source name specified in the connection string: "BLUDB". SQLCODE=-1531 Honestly, I had no idea what was going on. But after doing a little searching, I found this post on StackOverflow about the same problem. It had no real definite answer, but it leads me to this tutorial. Basically, I had a couple of stuff in the INSTALLED_APPS list like so: INSTALLED_APPS … -
Pass Authentication Basic without access to header
I am trying to create a mobile app in Thunkable x. It allows for cross-platform development. The problem that I have encountered is that they don't have an option where you can set dynamic data in the header. I have it so that users can enter a username and password then it will send it to my Django server where it will return the base64 of the login credentials. I have to send the credentials to my second API where it will authenticate and return the information that I want. Since I cant Access the Headers is there a way in which I can send the authentication that is not in the header? The body is able to be edited. -
How to control a variable from the Django template and increment it
I have a problem creating a slideshow (well more like a one way slideshow) with random sequence every time, and no repeated pictures. I do not know how to connect the "next" button with the previously made sequence and is it possible for the template to increment a python counter. def ChemistryView(request): all_private_keys = PostForChemistry.objects.all() list_of_private_keys = [post.id for post in all_private_keys] random_ids = random.shuffle(list_of_private_keys) priv = list_of_private_keys[0] i = 1 querysetforchem = PostForChemistry.objects.get(pk=list_of_private_keys[0]) context = { "querysetforchem" : querysetforchem, "list_of_private_keys" : list_of_private_keys } return render(request, 'main/chemistry.html', context) I want a single id object on screen at a time and for it to increment not to the bigger one, but to the next in the random list. -
navigating with animate, the navigation hides the top of the target area. How can I make the upper part visible in this case?
I have a question. When navigating with animate, the navigation hides the top of the target area. How can I make the upper part visible in this case? code $(".go_btn").click(function(){ const number = $(".go_input").val(); if(number == 1){ $('html, body').animate({ 'scrollTop' : $("#index_first").offset().bottom }); } $('html, body').animate({ 'scrollTop' : $("#index_"+number).offset().top }); }) -
Django 2.2 - Testcase - client.logout() method does not log out user
I am writing tests for my simple Django web application, checking if user can login and logout correctly. Views:user_login and user_logout def user_login(request): if request.method == 'POST': email = request.POST.get('email address') password = request.POST.get('password') user = authenticate(username=email, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('main_page:index')) else: print("\nWARNING: invalid login detected\n\nemail: {}\npassword: {}\n".format(email, password)) messages.error(request, 'Ivalid email or password. Try again.') return HttpResponseRedirect(reverse('users:login')) else: return render(request, 'users/login.html', {}) @login_required def user_logout(request): messages.add_message(request, messages.INFO, 'See you Space Cowboy!') logout(request) return HttpResponseRedirect(reverse('main_page:index')) And the tests themself: class LoginLogoutTests(TestCase): def setUp(self): User = get_user_model() self.user = User.objects.create_user(email='test_user@email.com', password='S6y4Mb9Aqfu79YcF') print("\nsetup") def tearDown(self): self.user print("teardown\n") def test_login(self): # test if email is equal self.assertEqual(self.user.email, 'test_user@email.com') # test authentication self.assertTrue(self.user.is_authenticated) self.assertFalse(self.user.is_anonymous) # test if login request index.html self.assertTrue(self.client.get('main_page.index.html')) # test login with valid credentials self.assertTrue(self.client.login(email='test_user@email.com', password='S6y4Mb9Aqfu79YcF')) # test login with invalid credentials self.assertFalse(self.client.login(email='test_user@email.com', password='password')) print("test login") def test_logout(self): self.client.logout() self.assertTrue(self.user.is_authenticated) self.assertFalse(self.user.is_anonymous) print("test logout\n") Tests return this output: (venv) [user@manjaro django-project]$ ./manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). setup test login teardown setup test logout teardown .... ---------------------------------------------------------------------- Ran 4 tests in 0.515s OK Destroying test database for alias 'default'... What goes here wrong? EDIT: I rebuilt user model … -
How to add external css/js in django2.2
How do i add an external css/js to my html template when working with django i've tried some previously asked questions reply but seem like they're outdated and below is one of the procedure i followed # after making sure the installed app has contrib.static then i make a file called static/my_apps/my.css {%loadstatic%} <link rel='stylesheet' href="{%static 'my_apps/my.css' %}"> # i also tried {%loadstaticfile%} but none work -
Django FormModel some fields aren't saved
I'm using a FormModel in Django but some fields are not saved to the database... models.py file from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.forms import ModelForm # Create your models here. class Bill(models.Model): image_name = models.CharField(max_length=150) upload_date = models.DateTimeField(default=timezone.now) image = models.ImageField() description = models.TextField(blank=True) result = models.CharField(max_length=1000) uploaded_by = models.OneToOneField(User, on_delete=models.CASCADE, null=True) def __str__(self): return str(self.result + self.description) forms.py file from django import forms from django.db import models from django.forms import ModelForm from .models import Bill class BillForm(ModelForm): class Meta: model = Bill fields = ['image', 'description'] exclude = ['result', 'image_name', 'upload_date', 'uploaded_by'] views.py file def upload(request): if request.method == 'POST': form = BillForm(request.POST, request.FILES) if form.is_valid(): form.image_name = request.FILES['image'] form.upload_date = datetime.now() form.uploaded_by = request.user form.result = "something" form.save() return redirect('cism-home') else: form = BillForm() return render(request, 'auth/upload.html', {'form': form}) So the image and description fields are saved but other fields are not. Any ideas why is that? -
How to pass request over Django channels WebSocket and call Django view
I'm working on a single page application with Django, and would like to use WebSockets, and therefore Channels. To keep things simple, I think I want to handle all server communication over a WebSocket alone, rather than adding XHR (XML HTTP Request) into the mix. I'm using channels from the get-go since there will be a lot of data pushed from the server to the client asynchronously. With regular Django, a conventional request made to https://example.com/login or https://example.com/logout or whatever and the Django URL router will decide what view to send it to. Instead, I would like to have the user perform their action in the client, handle it with Javascript, and use the WebSocket to send the request to the server. Since I'm using Django-allauth, I would like to use the provided Django views to handle things like authentication. The server would then update the client with the necessary state information from the view. My question: how can I process the data received over the WebSocket and submit the HTTP request to the Django view? I can picture what would happen using XHR, but I'm trying to avoid mixing the two, unless someone can point out the usefulness in … -
Gunicorn ModuleNotFoundError: No module named 'django'
I'm trying to deploy a django application by following this tutorial. At the time of starting gunicorn, I use this command: gunicorn -b 127.0.0.1:8000 wsgi:application, being inside the folder where my wsgi.py is located. wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() And I get the following error: [2019-07-19 20:54:39 -0300] [7786] [INFO] Starting gunicorn 19.9.0 [2019-07-19 20:54:39 -0300] [7786] [INFO] Listening at: http://127.0.0.1:8000 (7786) [2019-07-19 20:54:39 -0300] [7786] [INFO] Using worker: sync [2019-07-19 20:54:39 -0300] [7789] [INFO] Booting worker with pid: 7789 [2019-07-19 20:54:39 -0300] [7789] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/usr/local/lib/python3.6/dist-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/usr/local/lib/python3.6/dist-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.6/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.6/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/usr/local/lib/python3.6/dist-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.6/dist-packages/gunicorn/util.py", line 350, in import_app __import__(module) File "/home/ubuntu/renato-sfera/mysite/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' [2019-07-19 20:54:39 -0300] [7789] [INFO] Worker exiting (pid: 7789) [2019-07-19 20:54:39 -0300] [7786] [INFO] Shutting down: Master [2019-07-19 20:54:39 -0300] [7786] [INFO] Reason: Worker failed to boot. What can … -
Django Rest Framework: get multiple source fields from reverse relation
My models: class A(models.Model): name = models.CharField('Name', max_length=250) content = models.TextField('Content') timestamp = models.DateTimeField(auto_now_add=True) b = models.ForeignKey('bs.B', blank=True, null=True, verbose_name='b', related_name='as') class B(models.Model): name = models.CharField('Name', max_length=250) description = models.TextField('Description') timestamp = models.DateTimeField(auto_now_add=True) I want to serialize my B model and include multiple fields in it, but not all of them. Creating serializer like this: class BSerializer(serializers.ModelSerializer): a_items = ASerializer(many=True, read_only=True, source='as') class Meta: model = B fields = '__all__' gives me B objects with a_items field, containing all of A fields, but I would like to get only name and content. I've seen this question and the answer, but unfortunately, since DRF 3.0, it no longer supports field_to_native() method. I would be grateful for any kind of hints where to start with this, since even trying to add source='as.name' doesn't seem to work and related objects just disappears. I tried with some random string following as. and it still does not fail, even though I would expect that. -
How to make REST API to iterate all items in a table
I have image slide show UI to display all image in a db table, one by one, randomly. I want to use REST API to get the image by AJAX call. In each call, if the parameter passed to server is image id in a db table, how to make sure all image get displayed? For example, file_table = [1, 2, 3, 4, 5, 6], image_list = [5, 2, 3]. 'image_list' is db query result of table 'file_table'. Some item in file_table should not be displayed. Display order is 5, 2, 3. Since REST API is stateless, where 'image_list' should be stored and tracked, so that image '5', '2', '3' can be retrieved by REST API, one by one? -
Can't figure out a way set the DOC file permission for single,multi or Enterprise user
(https://i.stack.imgur.com/wxGXK.png) I have been working on a Django project where a user is allowed to download the DOC file after he makes payment for the file. But I can't figure out a way to restrict this doc file from being forwarded or copied. Please Help!! Here is the Image if anyone can help. -
'NoneType' object has no attribute 'get' when the object is not type None
I am trying to make an application that allows a view of all of a customer's financial portfolio (in this case that's various stocks, mutual funds, and "other" like a 401k) I have a QuerySet of mutual funds filtered by customer created in my views.py file that I am trying to pass to the html template and render the list. I am running into the error in the title, though: 'NoneType' object has no attribute 'get'. I have verified via print statements that the QuerySet is not of type None, and all the data I want to use is returned correctly when I store it in a variable in my view. I have a everything working for stocks, and it has identical functionality that works just fine, so I can't figure out the difference and why one works but the other doesn't. What would be causing this error? models.py class Stock(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='stocks') symbol = models.CharField(max_length=10) name = models.CharField(max_length=50) shares = models.DecimalField(max_digits=10, decimal_places=1) purchase_price = models.DecimalField(max_digits=10, decimal_places=2) purchase_date = models.DateField(default=timezone.now, blank=True, null=True) def created(self): self.recent_date = timezone.now() self.save() def __str__(self): return str(self.customer) def initial_stock_value(self): return self.shares * self.purchase_price def current_stock_price(self): symbol_f = str(self.symbol) main_api = 'https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=' api_key … -
solve this django problem i saw in heroku when i was deployoing
self.stop() 2019-07-19T20:44:36.871606+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 393, in stop 2019-07-19T20:44:36.871764+00:00 app[web.1]: time.sleep(0.1) 2019-07-19T20:44:36.871769+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 245, in handle_chld 2019-07-19T20:44:36.871953+00:00 app[web.1]: self.reap_workers() 2019-07-19T20:44:36.871958+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 525, in reap_workers 2019-07-19T20:44:36.872299+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2019-07-19T20:44:36.872338+00:00 app[web.1]: gunicorn.errors.HaltServer: -
Many-to-many relationship based on two optional fields in Django
I have these two objects (left out the irrelevant fields): class Item(models.Model): id = models.BigAutoField(primary_key=True) group_id = models.IntegerField(blank=True, null=True) class Observation(models.Model): item_id = models.IntegerField(blank=True, null=True) group_id = models.IntegerField(blank=True, null=True) Joining them is based on either the Observation's item_id or group_id: SELECT o.* FROM observations o JOIN items i ON (i.id = o.item_id OR i.group_id = o.group_id) ... Can such type of many-to-many relationship be described in the models or do I need to write a custom field? -
Django GraphQL documentation explorer encoding
I have a problem with GraphQL documentation explorer. As you can see on the picture, it has problems with russian text, it shows some, I guess, twice encoded strings like "\\u041c\\u043e\\u0441". How to fix this? -
How do something when i change a field on the django admin for a model
I have currently a boolean field called "is_active" on a model. Whenever i set this field manually in the django admin to True (Initially it it's false) i want it to do a certain action. How can i trigger this field on django to do this certain action when it is set to true? I heard about a save_model() method but i don't know how it works. class Company(models.Model): name = models.CharField(max_length=100, unique=True) is_active = models.BooleanField(default=False) def __str__(self): return self.name -
Django - Connect Users as "Friends"
I am trying to implement the concept of "connected users" in my project. The project I am working on is cfe's 'tweetme' - course on udemy. I changed the below to: accounts/models.py def friends(self, user, limit_to=1): profile = user.profile following = profile.following.all() following = profile.get_following() qs = self.get_queryset().order_by("?").filter(user__in=following).distinct().exclude(id=profile.id)[:1] return qs . So if a user follows another user, he will see him in his friends_list. It works for the users, but not for the posts associated to them. How can I change it so that both users must follow each other to get connected and see the posts of the other user? Can't I just do for user in... infollowing + getfollowing = friends? def toggle_follow(self, user, to_toggle_user): user_profile, created = UserProfile.objects.get_or_create(user=user) # (user_obj, true) if to_toggle_user in user_profile.following.all(): user_profile.following.remove(to_toggle_user) added = False else: user_profile.following.add(to_toggle_user) added = True return added def is_following(self, user, followed_by_user): user_profile, created = UserProfile.objects.get_or_create(user=user) if created: return False if followed_by_user in user_profile.following.all(): return True return False . Is there any way that this toggle_follow function notifies both users? Doesn't need to be async, a pop-up after the next refresh/login would be nice too, for a start. Thank you for any help / resource on this topic