Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ? -
How to get a queryset with first child product of a parent product?
I have this table(https://prnt.sc/s1ssxx), where I want to fetch all the products with structure standalone and only first variant(child) of a parent product. i.e(excluding all the products with structure "parent", and just keeping first child product of all parent products). from django.db.models import Count, F, Value parent_ids = Product.objects.filter(user_id=user_id,structure=Product.PARENT).values_list('id', flat=True) qs = Product.objects.filter(user_id=user_id).exclude(structure=Product.PARENT).annotate(p=F('parent_id')).distinct('parent_id') I tried this query, but I am using MySQL as Database backend, so it complains about error: "DISTINCT ON fields is not supported by this database backend" , it can only be used this way by other database backends such as Postgres so I can not use distinct with any field name. How can I fetch these records in an optimized way with minimum hits on DB? -
Django Model's Value Error while inserting data into model
I am trying to insert form-data into models User and UserGroup using APIView. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=False, null=False) last_name = models.CharField(max_length=255, blank=False, null=False) profile_picture = models.ImageField(upload_to='profile_pictures/', max_length=None, null=True, blank=True) is_active = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = 'email' class UserGroup(models.Model): user = models.ForeignKey(User, related_name='user_id', on_delete=models.CASCADE, blank=False) role = models.ForeignKey(Role, related_name='role_id', on_delete=models.CASCADE, blank= False) I am able to insert data into model User but when I try to do the same with the model UserGroup it returns an error. ValueError: Cannot assign "17": "UserGroup.user" must be a "User" instance. I want this API to create a user and assign a role immediately to the newly created user by inserting role_id and user_id in model UserGroup. I have created two different serializer UserSerializer and UserGroup serializer and both has its own create method to push an instance into model. Also, in post request payload I am accepting all the fields of User model but for UserGroup model I am just accepting role field and not the user field as its value needs to be generated once the user is created. I will have to use transaction as well to roll back if in case a … -
NoReverseMatch at /checkout/ - Django Website
django.urls.exceptions.NoReverseMatch: Reverse for 'update_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart\/(?P[^/]+)$'] [18/Apr/2020 14:05:02] "GET /checkout/ HTTP/1.1" 500 157543 <--- this is the error message I am getting in terminal when I try to go onto the checkout page. view.html {% for item in cart.products.all %} <tr><td> {{ item }} </td><td>{{item.price}}</td> <td><a href='{% url "update_cart" item.slug %}'> Remove</a></td></tr> {% endfor %} </table> <br/> <a href='{% url "checkout" %}'>Checkout</a> {% endif %} </div> </div> {% endblock content %} views.py for orders from django.urls import reverse from django.shortcuts import render, HttpResponseRedirect # Create your views here. from carts.models import Cart def checkout(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse("fuisce-home")) context = {} template = "fuisce/home.html" return render(request, template, context) urls.py from django.urls import path from . import views from carts import views as cart_views from orders import views as order_views urlpatterns = [ path('cart/', cart_views.view, name='cart'), path('cart/<slug>', cart_views.update_cart, name='update_cart'), path('checkout/', order_views.checkout, name='checkout'), ] I can't figure out where the problem is occurring. Any solutions would be greatly appreciated! -
Failed to connect to server postgres django
I configured postgresql on the server as I was told by technical support, but when I go to the page and try to send mail, an error appears: OperationalError at /decision/livingrooms/kitchen/provans/ не удалось подключиться к серверу: В соединении отказано Он действительно работает по адресу "caparolcenterspb.ru" (217.107.219.83) и принимает TCP-соединения (порт 5432)? -
Modify login.html file in Django
{% extends '_base.html' %} {% load crispy_forms_tags %} {% block title %}Log In{% endblock title %} {% block content %} <section id="homeSection" style="width: 1250px;height: 1080px;padding: 40px;background-repeat: no- repeat;background-position: top center;background-size: cover;"> <div > <h2>Log In</h2> <form method="post"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-success" type="submit">Log In</button> </form> </div> </section> {% endblock content %} This HTML code is used for the login page. I need to modify the login page with CSS and bootstrap files. I am a beginner to DJANGO. Please suggest me how to modify the this login.html. -
Error in base_name argument in register() in Django Rest Framework
I'm working in Django Rest Framework.And I have defined a view set in the views.py file like this: from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets from profiles_api import serializers class HelloApiView(APIView): """Test API View""" serializer_class = serializers.HelloSerializer def get(self,request,format=None): """Returns a list of APIView features""" an_apiview = [ 'Uses HTTP methods as functions (get, post, patch, put, delete)', 'Is similar to a traditional Django View', 'Gives you the most control over your logic', 'Is mapped manually to URLs', ] return Response({'message': 'Hello!', 'an_apiview': an_apiview}) def post(self, request): """Create a hello message with our name""" serializer = self.serializer_class(data=request.data) if serializer.is_valid(): name = serializer.validated_data.get('name') message = f'Hello {name}!' return Response({'message': message}) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) def put(self, request, pk=None): """Handle updating an object""" return Response({'method': 'PUT'}) def patch(self, request, pk=None): """Handle partial update of object""" return Response({'method': 'PATCH'}) def delete(self, request, pk=None): """Delete an object""" return Response({'method': 'DELETE'}) class HelloViewSet(viewsets.ViewSet): """Test API ViewSet""" def list(self, request): """Return a hello message.""" a_viewset = [ 'Uses actions (list, create, retrieve, update, partial_update)', 'Automatically maps to URLS using Routers', 'Provides more functionality with less code', ] return Response({'message': 'Hello!', 'a_viewset': a_viewset}) And I have … -
How to serialize a list of strings
I'm having an rather easy problem with my serializer. My view: @api_view(['GET']) def get_recipes_list(request): recipes = Recipe.objects.all() serializer = RecipeListSerializer(recipes, context={'request': request}, many=True) return Response(serializer.data) My serializer: class RecipeListSerializer(serializers.Serializer): name = serializers.CharField() Output I'm getting: [ { "name": "Gelato1" }, { "name": "Gelato2" }, ] What I desire is: [ 'name': [ 'Gelato1', 'Gelato2', ] ] I tried: recipes = Recipe.objects.all().values_list('name', flat=True) So that the QuerySet has a list of names, but I'm getting an AttributeError. I'll be grateful for any advices. -
How to implement the tags in django similar to stackoverflow tags in django?
Im learning django 3(can build simple blogs) and trying to develop problem registering application. i was curios what things are involved to create tags like shown in screenshot (CCs email, tags) , when i enter email address and press enter it gets set , similarly when i enter some string and press enter the string is saved in Tag section. what is the field type used(in database model) for such and how relationship is handled (so far my understanding is it must be many to many as multiple Tag string can be associated to multiple issue but is it so simple like this ? ), how effective search can be implemented based on the tags and other bits/pieces of library implemented you know/use - I would appreciate suggestions and helpful links -
scroll websites with django
I'm currently working on a simple scroll website with nothing really difficult (I could almost use plain html/css/javascript but it's a bit of practicing and I will maybe add a blog). And as it is simple I was wondering how to do it properly with Django. So here is my question, I have a homepage template that is actually the website and I don't really get how I split my different part in different apps. For exemple I have a contact form, do I need to split it in another app and then include it in the basic template ? I want to add a galery with image in a database, do I create an app for that ? And the other question that goes along is how do I code an app that is not returning httpresponse but just html to put it in another template and do I still need views ? I would like to do a bit like a standard form in django where you do : form.as_p or form.as_table so maybe: galery.as_slideshow So my questions are quite novice and open but someone could give me some reading to get going, I would be really happy … -
Django-allauth does not use custom socialaccount templates
I copied the django-allauth account and socialaccount templates under my_django_project/templates/account my_django_project/templates/socialaccount respectively. Allauth successfully reads the overwritten account templates but it does not read templates/socialaccount/snippets/provider_list.html my settings.py looks like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Deployed Django app on heroku and got heroku log error
I have built a Django app and deployed it to Heroku but when I try to run Heroku open I get an error. It is showing me error=h10, desc="App Crashed" and also showing me [info] Worker failed to boot. I don't know how to solve it? here are my Procfile web: gunicorn DEMOPROJECT.wsgi:application --log-file - and here are my settings.py and wsgi.py file settings.py """ Django settings for DEMOPROJECT project. Generated by 'django-admin startproject' using Django 2.2.4. import os from django.contrib.messages import constants as messages # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '^8&=+ce4*v^g#q&+%ougrid$7&4y2yc2%%=a5uer7#yc6i#ez7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['letsdoit-s.herokuapp.com', '127.0.0.1:8000'] # Application definition INSTALLED_APPS = [ 'DEMOAPP.apps.DemoappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'DEMOPROJECT.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'DEMOPROJECT.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } …