Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add chatting application to django website
I want a very basic simplest way for users on website to chat. How can I do it? can I integrate any chat platform with it, like hangouts or etc. I was thinking I can use emails in any way but that would so brute. suggest easy to implement and basic methods because it is a large website and chatting is not its core part. -
Google Maps API Error: This API key is not authorized to use this service or API. Places API error: ApiTargetBlockedMapError
I've started getting this error from a Google Maps widget within a CMS I use: This API key is not authorized to use this service or API. Places API error: ApiTargetBlockedMapError The error message provides a helpful link to this page, which includes the following text: ApiTargetBlockedMapError Error The Maps JavaScript API has not been authorized for the used API key. Please check the API restrictions settings of your API key in the Google Cloud Platform Console. See API keys in the Google Cloud Platform Console. For more information, see Using API Keys. I know Google has tweaked this API in the past, so I went to the console and checked the permissions given for the key I am using. It includes these four permissions, include the Maps JavaScript API permission: Geocoding API Maps Embed API Maps JavaScript API Maps Static API The only part not working is the address auto-complete. When I change to Don't Restrict Key mode so the key works with all services, it works fine. Any idea which service checkbox I might be missing? I'm wondering if Google is just displaying the wrong error. Any ideas? -
Accessing a Subclass Model Data while Searching for it's parent class in Django
I don't really know how to explain my problem well enough but i'll give it a shot. We have the default User model, an extention to an Employee model and then an extension to that, Timesheet. Each employee can have many timesheets and each Employee only has one User. I want to create code which searches for the username, stored in User and then returns all the timesheet objects for that user. This is my current view Given the code Views.py: class EmployeeSearchView(PermissionRequiredMixin, ListView): permission_required = ('zapp.can_approve') model = User template_name = 'zapp/search_timesheet.html' def get_queryset(self): query = self.request.GET.get('q') object_list = User.objects.filter(username__iexact=query) return object_list and my current template {% extends 'zapp/base.html' %} {% block content %} <h2>Submit new timesheet</h2> <form method="POST" class="timesheet-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} If no solution can be provided with my little information where could I find in the docs something which talks about this? Thanks! -
Django.forms.fields.booleanfield Object at when iterating through a list of fields
I want to iterate through a list of checkboxes. When I use a single checkbox it works, but when I iterate through the checkboxes, I get <DJANGO.FORMS.FIELDS.BOOLEANFIELD OBJECT AT 0X7FA2DA62B470> <DJANGO.FORMS.FIELDS.BOOLEANFIELD OBJECT AT 0X7FA2DA5A5940> It shouldn't be a list or tuple issue like in this one or similar questions I found. my forms.py: class TestForm(forms.Form): toggles = [forms.BooleanField(label="A Checkbox", required=False), forms.BooleanField(label="A second Checkbox", required=False)] single_toggle = forms.BooleanField(label="A single Checkbox", required=False) my template: {% for toggle in form.toggles %} {{ toggle }} {% endfor %} {{ form.single_toggle }} Expected output: Three checkboxes Actual output: <DJANGO.FORMS.FIELDS.BOOLEANFIELD OBJECT AT 0X7FA2DA62B470> <DJANGO.FORMS.FIELDS.BOOLEANFIELD OBJECT AT 0X7FA2DA5A5940> and a single checkbox. -
django.contrib.auth login() returning None issue
I am new to django and I have been trying to implement login system for my django project. template_name = 'rest_framework/login.html' if request.method == 'POST': email = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=email, password=password) print (login(request,user)) login(request,user) return redirect('core:home') return render(request, template_name) For some reason, the login function which I have imported from django.contrib.auth is returning None even when user has the correct user object after authenticating and request has POST request object. This is resulting in the user not getting added to the session and hence when I redirect it to core:home, I am getting AnonymousUser in request.user. Help would be appreciated. PS: I have written a custom backend for authentication. -
Customizing Django GenericRelation content_type values in Admin add/change view
My models are using GenericForeignKey and GenericRelations. For simplification my models structure is following: class BaseModel(models.Model): name = models.CharField(max_length=100) model_labels = models.GenericRelation('ModelLabel', related_query_name='%(class)s') model_types = models.GenericRelation('ModelType'), related_query_name='%(class)s') class Meta: abstract = True class ModelA(BaseModel): fieldA = models.CharField(max_length = 50) class ModelB(BaseModel): fieldB = models.CharField(max_length = 50) class ModelLabel(models.Model); label = models.CharField(max_length = 50) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() model_object = GenericForeignKey('content_type', 'object_id') class ModelType(models.Model): type = models.CharField(max_length = 50) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() model_object = GenericForeignKey('content_type', 'object_id') class Unrelated(models.Model): name = models.CharField(max_lenght = 50) The problem I am facing is in admin view for ModelLabel and ModelType. Right now, out-of-the-box I am getting 3 fields: Label or Type, Content type and Object id. Yes, this is correct according to the model. But in Content type I am getting not only ModelA and ModelB as an options. I'm also getting Unrelated and most of the individual fields of different models. According to documentation: Instances of ContentType represent and store information about the models installed in your project, and new instances of ContentType are automatically created whenever new models are installed. According to this Unrelated can appear in the values, but models' fields shouldn't. So why they … -
Reverse for 'beriNilai' with arguments '('SI 43 01',)' not found. 1 pattern(s) tried: ['grader/beriNilai/(?P<pk>\\d+)$']
im trying to print a data from table called t_pengguna where the kelas field is equal to the data that is being clicked by the user, so im trying to make something like select nama from t_pengguna where kelas = ....., i tried to pass the clicked data using parameter, but i got this reverse error, here is my urls.py file: url(r'^beriNilai/(?P<pk>\d+)$', tambahNilai, name='beriNilai') and here is my views.py file: def tambahNilai(request, pk):return render(request, 'grader/beriNilai.html', {'siswa' : t_pengguna.objects.filter(kelas=pk)}) and here is my html file, where i make the button to pass the parameter: <td> <a class="btn btn-sm btn-outline-primary" href="{% url 'beriNilai' matkuls.kelas %}"> <i class="fa fa-pencil-square-o" aria-hidden="true"></i> beri nilai </a> </td> anyhelp will be appriciated, thanks before, stay healty! -
Graphene mutation with many to many relationship arguments
I'm not sure it will be understandable... I have a model Reservation with a service which actually is a ManyToManyField. Actually I'm creating a CreateReservation mutation and one of the required field is service but I don't know how to enter more than one (service arguments). class CreateReservation(graphene.Mutation): reservation = graphene.Field(ReservationType) class Arguments: dog = graphene.String() date = graphene.types.datetime.DateTime() service = graphene.String() def mutate(self, info, dog, date, service): reservation = Reservation(dog=dog, date=date, service=service) reservation.save() return CreateReservation(reservation=reservation) -
2 step authentication with django rest framework
i am looking to implement a 2 step authentication into my django application. Previously , i have used the packaged django-two-step-auth , however im not fully sure if it is react and drf compatible. Has anyone successfully implemented a 2 step authentication process in their django x react application? I would love to know what packages there are out there. -
Best type of SQL to use with Django?
Is MySQL a good option to use with Django? I'm a beginner to Django -
How would you handle creating a response for a method that checks if an object is valid?
Lets say I have a Model in my models.py that stores financial transactions. The model has a method called is_valid() which basically checks that the object adheres to a bunch of business logics. This method has now got quite long, it does about 20 checks on the object and looks something like this: def is_valid(self): if self.something is something: return false if self.something_else is something: return false ... return true So far this has worked great, but I've now got to the stage where I no longer need to just know if an object is valid, but if it's not valid I need to know which check it failed. So something like: def is_valid(self): if self.something is something: return error1 if self.something_else is something: return error2 ... return true But, if the object has failed multiple checks then I'd want to know all the checks it has failed. What would be the most clean way of handling this? My code also has lots of lines that check is_valid() returns true, so ideally it would still return true if the object is valid, but if not valid then it would let me know which conditions it failed. -
Django Tutorial or Online Class
I am searching for a good Django tutorial and an online class. All recommendations will be very much appreciated. I've looked at tutorialspoint and a few others, but would like something more complete with more examples. -
Does Celery cache tasks? How can I reload changes in a dev environment?
When using Celery, Docker, RabbitMQ and Django (with django-celery-results and django-celery-beat) I am able to load a simple task following the tutorial. However, when I make changes to the task and reload the server (docker-compose down, docker-compose up) the changes are not reflected. Does Celery cache tasks somewhere / how to I reload them when in a dev environment? The tutorial sets CELERY_CACHE_BACKEND = 'django-cache' but I would assume this is destroyed by docker-compose down? celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() proj/__ init __ .py: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) tasks.py: from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def hello_world(): return print('hello world!') settings.py: CELERY_BROKER_URL = 'pyamqp://rabbitmq:5672' CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_BEAT_SCHEDULE = { 'hello': { 'task': 'proj.tasks.hello', 'schedule': crontab() # execute every minute } } -
NoReverseMatch in Django?
I am working on a blog site and I've got an error NoReverseMatch at / Reverse for 'about' not found. 'about' is not a valid view function or pattern name. base.html: <li><a href="{% url 'blog:about' %}">About</a></li> <li><a href="https://www.github.com">Github</a></li> <li><a href="https://www.linkedin.com">LinkedIn</a></li> urls.py: app_name = 'blog' urlpatterns = [ url(r'^$', views.PostListView.as_view(), name='post_list'), url(r'^about/$', views.AboutView.as_view(), name='about'), ] views.py: class AboutView(TemplateView): template_name = 'about.html' -
Is there a way to store data obtained using selenium into a database provided by django?
I want to store data obtained using selenium into a database provided by django. But I can't. Please tell me how to solve. The code below is my code. My project name is 'ebookranking' and app name is 'index' #kyobo.py from bs4 import BeautifulSoup from selenium import webdriver import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ebookranking.settings') import django django.setup() from index.models import Book def kyobo(): driver = webdriver.Chrome('C:\\Users\\insutance\\PycharmProjects\\chromedriver') driver.get('http://m.kyobobook.co.kr/digital/ebook/bestList.ink?cate_code=1&class_code=&barcode=&barcodes=&cate_gubun=&orderClick=&listCateGubun=1&listSortType=1&listSortType2=0&listSortType3=0&listSortType4=0&need_login=N&type=&returnUrl=%2Fdigital%2Febook%2FbestList.ink&reviewLimit=0&refererUrl=&barcodes_temp=&gubun=&ser_product_yn=&groupSort=1&groupSort2=0&groupSort3=0&groupSort4=0') driver.implicitly_wait(2) html = driver.page_source soup = BeautifulSoup(html, 'html.parser') titles = [] for n in range(1,31): title = soup.select_one('#list > li:nth-child('+ str(n) +') > div.detail > p.pubTitle > a') titles.append(title.text) driver.quit() return titles if __name__=='__main__': datas = kyobo() for t in datas: Book(title=t).save() The code below is my models code. #models.py from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length = 200) price = models.CharField(max_length = 10) def __str__(self): return self.title -
Is there a way to embed my django login form into my base.html template?
I am currently making a django school system, and have come across a dilemma. Whilst I have successfully made a functioning login system, all the tutorials I have seen include a separate page for the login form. Considering that my site is LOGIN ONLY ACCESS, I have an if statement on base.html template that will show content depending if the user is logged in or not. It shows the correct content if the user is logged in, however, I don't know how to embed my login form into the base.html so I can insert it into the if/else statement. Any easy ways to do this? I'll share my code if needed. -
unresolved import 'django.db'Python(unresolved-import)
I am new to Django and recently I tried to install Django in my Macbook but I am getting the above error. I believe that error is due to some wrong configuration. Steps followed: installed virtual env installed Python and PIP installed Django (Created demo app it started with no problem). files paths: Python: (which python) /Users/sankar/Desktop/Development/env/bin/python Django:'/Users/sankar/Desktop/Development/env/lib/python3.8/site-packages/django/' sys.path:sys.path ['', '/Users/sankar/Desktop/Development/env/lib/python38.zip', '/Users/sankar/Desktop/Development/env/lib/python3.8', '/Users/sankar/Desktop/Development/env/lib/python3.8/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8', '/Users/sankar/Desktop/Development/env/lib/python3.8/site-packages'] Please help me with the same. Thanks for the help in advance. -
Postgres connection pooling in django
i'm developing a Django application with Postgres Database and without ORM(using raw sql and psycopg2). how to use connection pooling in this case? i mean if a webserver like heroku creates an instance of django for each Httprequest how connection pooling should be implemented in this case? where should i put settings of connection pooling in application? -
Issue on installing GDAL on pycharm windows10
I have error when I install GDAL in my pycharm on windows10. I am using Python3.8. And try to install DjangoGeo by follow this guide. https://docs.djangoproject.com/en/3.0/ref/contrib/gis/tutorial/ Appreciate for any one who can solve my prob, I am very new to Python. I just started to learn it for my final year project. (django-demo-2) C:\Users\CHANG WEI HONG\PycharmProjects\django-demo-2\demo2\world\data>pip install GDAL Collecting GDAL Using cached GDAL-3.0.4.tar.gz (577 kB) Building wheels for collected packages: GDAL Building wheel for GDAL (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'C:\Users\CHANG WEI HONG\.virtualenvs\django-demo-2-djNsvbJD\Scripts\python.exe' -u -c 'import s ys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\CHANG WEI HONG\\AppData\\Local\\Temp\\pip-install-n0 szrwth\\GDAL\\setup.py'"'"'; __file__='"'"'C:\\Users\\CHANG WEI HONG\\AppData\\Local\\Temp\\pip-install-n0sz rwth\\GDAL\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\ n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\CHAN G WEI HONG\AppData\Local\Temp\pip-wheel-ke5_j8pv' cwd: C:\Users\CHANG WEI HONG\AppData\Local\Temp\pip-install-n0szrwth\GDAL\ Complete output (32 lines): running bdist_wheel running build running build_py creating build creating build\lib.win32-3.8 copying gdal.py -> build\lib.win32-3.8 copying ogr.py -> build\lib.win32-3.8 copying osr.py -> build\lib.win32-3.8 copying gdalconst.py -> build\lib.win32-3.8 copying gdalnumeric.py -> build\lib.win32-3.8 creating build\lib.win32-3.8\osgeo copying osgeo\gdal.py -> build\lib.win32-3.8\osgeo copying osgeo\gdalconst.py -> build\lib.win32-3.8\osgeo copying osgeo\gdalnumeric.py -> build\lib.win32-3.8\osgeo copying osgeo\gdal_array.py -> build\lib.win32-3.8\osgeo copying osgeo\gnm.py -> build\lib.win32-3.8\osgeo copying osgeo\ogr.py -> build\lib.win32-3.8\osgeo copying osgeo\osr.py -> build\lib.win32-3.8\osgeo copying osgeo\__init__.py -> build\lib.win32-3.8\osgeo Fixing build\lib.win32-3.8\gdal.py build\lib.win32-3.8\ogr.py build\lib.win32-3.8\osr.py build\lib.win32-3 .8\gdalconst.py build\lib.win32-3.8\gdalnumeric.py build\lib.win32-3.8\osgeo\gdal.py build\lib.win32-3.8\osg … -
django-tenant-schemas wont apply migration to tenant schema, only public
I have a multi-tenant django app using django-tenant-schemas. There is an SiteConfig app: settings.py: TENANT_APPS = ( ... 'siteconfig', ... ) INSTALLED_APPS = ( ... 'siteconfig', ... ) But my latest migration on that app won't apply to my tenants: $ ./manage.py migrate_schemas --shared [standard:public] === Running migrate for schema public [standard:public] Operations to perform: [standard:public] Apply all migrations: account, admin, ... siteconfig, sites, socialaccount, tenant, utilities [standard:public] Running migrations: [standard:public] Applying siteconfig.0007_siteconfig_access_code... [standard:public] OK As you can see it is only applying the migration to the public schema, and not my tenants. If I look at my tenant, it shows the migration there as unapplied: $ ./manage.py tenant_command showmigrations Enter Tenant Schema ('?' to list schemas): ? public - localhost test - test.localhost Enter Tenant Schema ('?' to list schemas): test account [X] 0001_initial [X] 0002_email_max_length admin [X] 0001_initial [X] 0002_logentry_remove_auto_add+ . . . siteconfig [X] 0001_initial [X] 0002_auto_20200402_2201 [X] 0003_auto_20200402_2218 [X] 0004_auto_20200402_2233 [X] 0005_auto_20200403_0947 [X] 0006_auto_20200403_1528 [ ] 0007_siteconfig_access_code < DIDNT APPLY! Why is it not applying to the tenant test and how can I get it to do that? -
Django nested serializers Many to Many
Here is what I'm trying solve if genre exit: find the PK that matches the "type" field link the result(s) with Movie class else: create the "type" or type(s) inside of Genre class "link" the key(s) with Movie Class Genre Serializer class GenreSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = ('type',) Movie Serializer class MovieSerializer(serializers.ModelSerializer): genres = GenreSerializer(many=True) class Meta: model = Movie fields = ( 'id', 'name', 'description', 'imdb_score', 'popularity', 'director', 'genres' ) def create(self, validated_data): genre_type = validated_data.pop('genres') movie = Movie.objects.create(**validated_data) for each_type in genre_type: g = Genre.objects.get_or_create(**each_type)[0] print(g.pk) movie.genres.add(g) return movie With the above code, I'm able to create a new movie with genre(s) but cannot create a new movie with existing genres. -
Convert python desktop applications to web applications
I have 5 python desktop applications that I have written using tkinter, and I would like to convert them to web apps. I know there is no easy way to do this, and I will have to re-do the entire front end, and I will have to use Flask or Django. I have also looked at CloudTk, but I am unable to find enough tutorials on how to use that. Is there any online tutorial that I can use as a reference to convert my applications? Thanks. -
Django Break Queryset into sub querysets based on param
I am looking for a "group_by" like functionality that will allow me to separate a django queryset into multiple querysets, grouped by a parameter (in my case, a date). I have a working solution, but I know it could be greatly improved if I knew a bit more about the more advanced functions. Here is my current (ugly) code below, to give you an idea of what I am specifically looking to do. class ClassesListView(ListView): model = Class context_object_name = 'classes' template_name = 'classes/ClassesListTemplate.html' def get_queryset(self): qs = super(ClassesListView, self).get_queryset() return qs.filter(start_datetime__gte = timezone.localtime(timezone.now())) def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) qs = self.object_list querysets = [] for i in range (0, 7): _date = timezone.localtime(timezone.now()) + timezone.timedelta(days=i) _qs = qs.filter(start_datetime__date = _date.date()) querysets.append( { 'date' : _date, 'qs' : _qs } ) context_data['querysets'] = querysets return context_data Any guidance would be greatly appreciated! -
ReactJS Django - How to render Many to Many field object instances in ReactJS form
I am currently working on a project that uses Django as the backend, and ReactJS as the frontend. I am new to ReactJS and the Django Rest Framework, and I encountered a problem when I was trying to render a form in ReactJS to create a 'Customer' object, as one of the fields was a Many to Many field that links to another model called 'Sales Department'. Hence, I am not too sure of how to render the relevant Sales Department objects for the user to select when creating a new Customer using ReactJS. Is there a way for the Sales Department objects to be passed through the API endpoint? I am currently only able to pass the Customer objects through the API endpoint, and am not sure how to pass both models in a single Viewset. Any help is appreciated and if I misunderstood any part of ReactJS or the DRF, please help to point me in the right direction, thanks! -
Is there a VS Code extension similar to Live Server but for Django?
There's an extension for VS Code called Live Server that auto refreshes the webpage as your editing your project. When you hit save, the page refreshes. I work with Django almost exclusively, and unfortunately I haven't found a way to do the same thing in a way that works with Django / Jinja templating. What's the best way to do this when working with a Django project?