Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Python "SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/docutils/"
PROBLEM Whatever I try to install from terminal with pip (macOS 10.12) I get this error message i may have installed and fully deleted homebrew before but I am not sure how to solve this Installs I run (bot cases same error message) pip install -r requirements.txt pip install django-storages ERROR MESSAGE WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django-storages/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django-storages/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django-storages/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django-storages/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django-storages/ Could not fetch URL https://pypi.org/simple/django-storages/: There was a problem confirming … -
django 'dict' object has no attribute 'sexo'
I've got the following code: def nuevo_animal_accion(request): if request.GET["caravana"]: animalnew = Animal form = request.GET.copy() caravana=form.get('caravana') idlotefk = Lote.objects.get(idlote=form.get('lote')) raza = form.get('raza') padre = form.get('padre') madre = form.get('madre') # fechanacimiento = form.get('nacimiento') sexo = form.get('sexo') animalnew.objects.create(caravana=caravana, idlotefk=idlotefk, raza=raza, padre=padre,madre=madre, sexo=sexo) # Ver como capturar errores por si no se pudo crear return HttpResponse("Se ingreso el nuevo animal") def listar_animales(request): animales = models.Animal.objects.values().all() for animal in animales: listaa[animal.caravana] = animal.sexo return render(request,"animal/listar_animal.html", listaa) Thing is that it gives me the atribute error. I've searched and there is a relative post (Django 'dict' object has no attribute 'user_id') but I can't figure out how can I use it on my code so please help. -
Pagination in Django GraphQL
I want to implement pagination with django-graphene. User and Post model: from django.db import models class User(models.Model): username = models.UsernameField() class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") title = models.CharField(max_length=191) GraphQL objects: import graphene from graphene_django import DjangoObjectType class UserType(DjangoObjectType): class Meta: model = User class PostType(DjangoObjectType): class Meta: model = Post Query for my username and posts: class Query(graphene.ObjectType): me = graphene.Field(UserType) def resolve_me(self, info): user = info.context.user return user I want pagination in nested model. query { me { username myPosts (first: 10, skip: 10) { id title } } } Regards. -
Questioning between django and two dates
I wrote an application with django. But I want to question between two dates. I wrote code as below but the results are empty I want to list the records between the two dates I gave. fields should be in the form dateTimeField API: http://127.0.0.1:8000/api/appointments/list?user=2&groupCode=1453&startDate=2020-04-17+10:00:00&endDate=2020-12-12+08:00:00 Model: ` user = models.ForeignKey(User, on_delete=models.CASCADE, default=0, blank=False) startDate = models.DateTimeField(blank=True) endDate = models.DateTimeField(blank=True) groupCode = models.CharField(max_length=50, blank=False) ` class AppointmentsListAPIView(ListAPIView): serializer_class = AppointmentsCreateSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filter_fields = ['customer', 'user', 'groupCode', 'startDate', 'endDate'] def get_queryset(self): print(self.request.query_params.get('startDate')) queryset = Appointments.objects.filter(user=self.request.query_params.get('user'), groupCode=self.request.query_params.get('groupCode'), startDate__gt=self.request.query_params.get('startDate'), endDate__lt=self.request.query_params.get('endDate')) return queryset ` Error RuntimeWarning: DateTimeField Appointments.endDate received a naive datetime (2020-12-12 08:00:00) while time zone support is active. RuntimeWarning) RuntimeWarning: DateTimeField Appointments.startDate received a naive datetime (2020-04-17 10:00:00) while time zone support is active. RuntimeWarning) -
Order of Execution of Migrations in Django
I am trying to understand how Django approaches migrations when it applies them to the database. In particular, suppose I am looking at this app: https://github.com/divio/aldryn-people/tree/master/aldryn_people/migrations I have inserted a breakpoint into each migration file, similar to this: def break_function(apps, schema_editor): print("Entered break_function() 0007") breakpoint() ... migrations.RunPython(break_function), When running tests, I get the following (Django tries to build a brand new database for testing and applies all the migrations to do so) Creating test database for alias 'extra'... Entered break_function() 0001 --Return-- > /home/user/sites/aldryn-people/aldryn_people/migrations/0001_initial.py(14)break_function()->No ne -> breakpoint() (Pdb) c Entered break_function() 0002 --Return-- > /home/user/sites/aldryn-people/aldryn_people/migrations/0002_auto_20150128_1411.py(8)break_func tion()->None -> breakpoint() (Pdb) c Entered break_function() 0003 --Return-- > /home/user/sites/aldryn-people/aldryn_people/migrations/0003_auto_20150425_2103.py(9)break_func tion()->None -> breakpoint() (Pdb) c Entered break_function() 0004 --Return-- > /home/user/sites/aldryn-people/aldryn_people/migrations/0004_auto_20150622_1606.py(8)break_func tion()->None -> breakpoint() (Pdb) c Entered break_function() 0005 --Return-- > /home/user/sites/aldryn-people/aldryn_people/migrations/0005_auto_20150723_1508.py(10)break_fun ction()->None -> breakpoint() (Pdb) c Entered break_function() 0006 --Return-- > /home/user/sites/aldryn-people/aldryn_people/migrations/0006_person_groups.py(9)break_function( )->None -> breakpoint() (Pdb) c Entered break_function() 0007 --Return-- > /home/user/sites/aldryn-people/aldryn_people/migrations/0007_copy_group.py(8)break_function()-> None -> breakpoint() (Pdb) c What I am wondering about is the order of execution. Why this order and not some other? I can see the logic of 0001_initial being the first (based on the name). After that, is it simply in the order specified in the naming of the … -
how to fetch like/dislike count from post model in django?
my post model class Post(models.Model): user=models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, related_name='post_owner') title=models.CharField(max_length=250) body=models.CharField(max_length=1000) slug=models.SlugField(max_length=100, blank=True) category_name=models.ForeignKey(Category,null=True, on_delete=models.SET_NULL) created_at=models.DateTimeField(auto_now=False, auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) published=models.BooleanField(null=True) publish_date=models.DateTimeField(blank=True, null=True) my likes model class Likes(models.Model): token=models.ForeignKey(User, related_name='users') obj=models.ForeignKey(Post, related_name='likes') my likes count model class LikesCount(models.Model): likes_count=models.PositiveIntegerField() obj=models.OnetoOneField(Post, related_name='likescount') now how to fetch likes count from posts models/views at the time of listing post Post.objects.filter(published=True).select_related(likescount__likes_count).order_by(likescount__likes_count) it will fetch only those posts whose likes_count is created in LikesCount model. i.e it is doing the LEFT INNER JOIN. it is not fetching the post whose likes_count are not created in LikesCount model. my logic for likes count: likes_count object is created when the first likes is created in the Likes model not when post is created. -
Django allauth social registration using token from frontend
In my backend I want to create a social account for the user after receiving the token in a request from frontend. Basically, the workflow would be: User logins to facebook in frontend Frontend sends user's token to backend Backend gets user's profile using the token received Backend populates the db with the user's profile. I am using django allauth, but haven't found any resource to help me implement this and I am not sure where to start. I've tried this, but it does not work: app = SocialApp.objects.get(provider="facebook") token = SocialToken(app=app, token=userToken) login = fb_complete_login(app=app, token=token, request=req) user_data = login.account.user.socialaccount_set.filter(provider='facebook')[0].extra_data It says that SocialAccount has no user. -
Django annotate with 'field' of 'related_name' of 'related_name'
I have three models : Domain Topic Post Topic has a foreign key to Domain and Post has a foreign key to Topic. Post has a field updated_on. I want to annotate last_updated field in Domain queryset which would contain the latest post object from Post . -
Unable to import 'django.db' pylint (import-error)
A friend and I are collaborating on a Django project. After he created the repository, I did a git pull and opened the code in Visual Studio Code. However, when I attempt to import any libraries I get this error with the error code Unable to import 'django.db' pylint (import-error). Can someone help in fixing this error please? -
How to deploy a Django and Vue with Docker?
I'm working on a project that is a Single Page Application, the backend is Django that serves a Graphql API and the frontend is a vuejs Project. When setting up the docker container I just prepared the container for Django and the Database thinking that Vue when built is just Html files and css and JS to be served. I was under the assumption that it didn't need containerization. Now that I prepared a part of the backend that I have tested with Insomnia (a an API testing tool) I tried setting it up with Vue. When working with Vue I noticed that I neglected a lot of parts. the CORS policy issues and more. I managed to solve those issues locally and Now I'm trying to have more overhead. if I'm having issues like this locally how am I supposed to be deploying this ? What is the correct way ? should I integrate Vue with django through another container for vue and use netwokring tricks to get it working ? Should I setup Vue inside the Django Container ? Should I add the cors policy local fixes to my dev brach and fix this with a good configuration … -
Django API Client Get Request with Payload
I am looking to see if this is possible. If I send a get request with body in postman I get back results matching what I need. Can we send a get request with a body using the APIClient? Here is my code; def setUp(self): self.client = APIClient() HistoryLog.objects.create(username='User1', log_time='2020-05-05', logon_time='08:00', logout_time='09:00') HistoryLog.objects.create(username='User2', log_time='2020-05-05', logon_time='08:30', logout_time='10:00') HistoryLog.objects.create(username='User3', log_time='2020-05-08', logon_time='08:40', logout_time='11:00') HistoryLog.objects.create(username='User4', log_time='2020-05-10', logon_time='08:50', logout_time='12:00') def test_get_data(self): payload = {'date': '2020-05-05', 'start_time': '06:00', 'end_time': '12:00'} res = self.client.get(HISTORY_URL, payload) self.assertEqual(res.status_code, status.HTTP_200_OK) -- this passes. self.assertEqual(len(res.data), 2) -- this always come back that res.data is zero -
How to use URL Python Django
I'm trying to learn Python Django with book "Example_Build_powerful_and_reliable_Python_web_applications" by Antonio Mele. Really sorry for probably stupid questions, but i'm very new. And sorry for my English, it isn't my native language. Have some problem with one of the example from the book. Do the same things as in the book, but URL's dont work. MODELS.PY from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'draft'), ('published', 'published') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.day, self.slug]) VIEWS.PY from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request): posts = Post.published.all return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, post): post = get_object_or_404(Post, slug = post) return render(request, 'blog/post/detail.html', {'post': post}) URLS.PY from django.urls import path from . import views app_name ='blog' urlpatterns = [ path('', views.post_list, name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), ] BASE.HTML <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> … -
Is there a simple way to check if all the properties in a queryset have same value?
If I have a Queryset containing a bunch of objects, is there a simple way to check that a property of all those objects contains a specified value? my_queryset = Employees.objects.filter(team='East1') Now I want to check that all these employees have cost_centre='E150'. At the moment I'm doing a loop through the queryset. -
update xml data in sql server from django
I have a sql server database with xml object. table template: type data 1 <InputNumber type="int" min="0" max="100" title="[1a] Indicate the percentage of"><\value> 2 <InputNumber type="int" min="0" max="100" title="[1b] Indicate the percentage of"><\value> i need to get the template based on the type and fill value and update it in the another table with the value. for example if i want a teplate of type 2: then i need get the template of type 2 file the value and update it in the another table table detail: name type data a 2 <InputNumber type="int" min="0" max="100" title="[1b] Indicate the percentage of"><value>3<\value> How do i do it, i am new to django and sql, i do not now either to update it from the django application or write a stored procedure of sql server Please guide me -
Keeping url same while updating contents of page after form submission using Django
I built an html form using the <form> tag and not using built in Django forms. The form asks for name and age. What I want to do is that after the user fills the form, the url of the page is kept same, while the contents of the page are changed to display name and age. How can I do that? <html> <head> <title>Form</title> </head> <body> <form method="post" action="aftersubmit"> {% csrf_token %} <input placeholder="yourname" name="name"> <br> <input placeholder="your age" name="age"> <br> <input type="submit" value="Submit"> </form> </body> </html> from django.shortcuts import render,redirect # Create your views here. def formpage(request): return render(request,'formhtml.html') def aftersubmit(request): name = request.POST['name'] age = request.POST['age'] dictionary = { "name":name, "age":age } print(dictionary) return redirect('formpage') My current code keeps the url same but does not modify the contents of the page. -
Django Rest Framework - How to retrieve model properties (field name, field type) and input into Rest API as data to be collected?
I am currently working on a project that uses Django as the backend, with the rest framework acting as an API endpoint for the frontend (ReactJS) to collect data and ultimately, using ReactJS to render the entire UI. However, right now, I am facing the issue of rendering the form in ReactJS as I do not want to manually type in the field names and field types into the form tag in the ReactJS component. Hence, I am hoping that I would be able to extract the model properties from Django, and pass the field names and field types to the API endpoint, so that the ReactJS frontend would be able to get the data and render the form fields accordingly. I have thought about passing in data through a model Serializer, but in that case, if there are no instances of that model, then the JSON object returned would be empty. Alternatively, if there is no way to extract the model properties in Django, then would it be possible for me to pass in the data manually by creating a new Serializer and View? and manually type in the required field names and field properties to be sent over … -
Permission denied error with django-celery-beat despite --schedulers flag
I am running Django, Celery, and RabbitMQ in a Docker container. It's all configured well and running, however when I am trying to install django-celery-beat I have a problem initialising the service. Specifically, this command: celery -A project beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler Results in this error: celery.platforms.LockFailed: [Errno 13] Permission denied: '/usr/src/app/celerybeat.pid' When looking at causes/solutions, the permission denied error appears to occur when the default scheduler (celery.beat.PersistentScheduler) attempts to track of the last run times in a local shelve database file and doesn't have write access. However, I am using django-celery-beat and appying the --scheduler flag to use the django_celery_beat.schedulers service that should store the schedule in the Django database and therefore not require write access. What else could be causing this problem? / How can I debug this further? -
How to expire a session in django?
There are some things i do not understand and i am not using in django, Like Serialize. From another question :How to expire Session in 5 mins? The sessions is confusing me.The sessions are active added in my installed apps and middle ware but.. I am using a simple login from the URL like this : path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), It generates a login form and work. How can i keep using this and now set Session expire time dynamically bases on user request to Remember Me Or what should i change and start over again to implement this whole idea ?