Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter objects in django based on json field where a key is list and based on number of list items mathched for each object?
I have a an object named canditade. class Candidate(models.Model): name = models.CharField(max_length=64) skills = models.JSONField() I have created objects like this Candidate.objects.create(name='mark',skills={'list':{'name':'python'}, {'name':'java'}, {'name':'sql'}, {'name':'django'} }) Candidate.objects.create(name='jeremy',skills={'list':{'name':'python'}, {'name':'java'}, {'name':'sql'}, {'name':'django'} }) Candidate.objects.create(name='jeremy',skills={'list':{'name':'python'}, {'name':'java'}, {'name':'sql'}, {'name':'flask'} }) I want to filter candidates where based on skills required vs skills present for alleast 75% match or 50% match. note : the percent can be dynamic. How should I query and filter the objects . if i enter skills like 'python','java','sql','docker'. and mention 75% match. I also want to know how the performance will be if i have to traverse over atleast a million records. -
how to convert UTC timezone DateTime in to local timezone using Django ORM query
class Book(models.Model): created_at=models.DateTimeField(auto_now_add=True) this datetime in utc timezone and i want to this datetime in to local timezone converted using query -
set tab-pane also to active when clicking nav-tab to active
Im trying to set a nav-tab to active and its corresponding tab-pane to active also. The problem here is whenever i click the offered_orders tab and choose for example page 2 in its pagination, it returns to allorders tabs. For it to return the correct page, it needs both the nav-tab and tab-pane set to active. However in my code below its not working. <div class="nav-tabs-custom"> <ul class="nav nav-tabs"> {% with active_tab="allorders" %} <li class="{%if active_tab == "allorders" %}active{%endif%}"><a href="#allorders" data-toggle="tab">All Orders</a></li> <li class="{%if active_tab == "offered_orders" %}active{%endif%}"><a href="#offered_orders" data-toggle="tab">Offered Orders</a></li> {%endwith%} </ul> <div class="tab-content"> <div class="tab-pane {%if active_tab == "allorders"%} active {%endif%}" id="allorders"> <div class="row"> <div class="col-md-12"> <table class="table table-bordered table-hover" border="0" style="width: 100%"> <thead> <tr> <th>Job Order No.</th> <th>Client Name</th> </tr> </thead> {%for allorders in allorders%} <tr> <td>{{allorders.oid}}</td> <td>{{allorders.client}}</td> </tr> {%endfor%} </table> {% if allorders.has_other_pages %} <ul class="pagination"> {% if allorders.has_previous %} <li><a href="?{{page_request_var}}={{ allorders.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in allorders.paginator.page_range %} {% if allorders.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?{{page_request_var}}={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if allorders.has_next %} <li><a href="?{{page_request_var}}={{ allorders.next_page_number }}">&raquo;</a></li> {% else %} … -
Django version upgrade 1.7 to 1.8 - content type issue
While upgrading django version from 1.7 to 1.8, I got a new migration called 0002_remove_content_type_name, after that I migrated that file, then I run my project, after that, it shows below error. (1054, "Unknown column 'django_content_type.name' in 'field list'") Then I checked the ContentType model in django.contrib files in packages, there I found the below code, class ContentType(models.Model): name = models.CharField(max_length=100) app_label = models.CharField(max_length=100) model = models.CharField(_('python model class name'), max_length=100) objects = ContentTypeManager() Due to the available of name field, I got the unknown column error, We should not edit the package file(like commenting the name field list in the model file), also we have to migrate the changes given when upgrading django version 1.7 to 1.8. Give me the best solution to resolve this issue. Thanks. -
Django rest framework display data from 2 other serializer in 1 view
I am currently doing an API for IOS application and i have 3 model, MyUser, Family and Schedule2. MyUser = Current user Family = Current user's family Schedule2 = A reminder (eg: birthday or an outing reminder kind) My idea is that in create schedule API, it will display: current userId, username, url(it is image url currently for testing) family id that is related to current user, relationship(the relationship between this family member and current user. eg: father, mother), url(same as above, image url) It is something like mobile app of facebook messenger where there is image showing the friends. And then the message/group chat below. Is there a way to do it ? I tried doing it but it got error and failed. What i did is insert related_name='family_mem' in Schedule2 userId, insert my_family = FamilySerializer(many=True, source='family_mem') into Schedule2Serializer and add my_family into the field. My expected output for ListCreateAPI : (this is only for when doing create function. I have a seperated API List to view schedule.) I only want to get the 3 details of current user as well as 3 details of all family member. Here is my code: models class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender … -
Minor Issue: Where is the better place to put User.objects.create_user in DRF?
Recently, I have reviewed my previous codes in Django thoroughly line by line. And I've got a minor issue. I have a preference to put ORM method to VIEW, not serializer. For example, I would like to make User.objects.create_user into APIView class like below. class SignUp(APIView): def post(self, request): serializer = SignUpSerializer(data=request.data) if serializer.is_valid(raise_exception=True): User.objects.create_user( email=serializer.validated_data['email'], password=serializer.validated_data['password1'], first_name=serializer.validated_data['first_name'], last_name=serializer.validated_data['last_name'], ) return Response(data=serializer.data, status=status.HTTP_201_CREATED) However, I've found many people code like below overriding create method in serializer. class SignUpSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) class Meta: model = User fields = ('pk', 'email', 'password1', 'password2', 'first_name', 'last_name') def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError('password should match') return data def create(self, validated_data): return self.Meta.model.objects.create_user( email=validated_data['email'], password=validated_data['password2'], first_name=validated_data['first_name'], last_name=validated_data['last_name'] ) I personally consider that serializer is more like data convertor, not reproducer. I would appreciate that you are able to share your opinion about this minor issue :) p.s I've said it minor issue because I am aware of this can be a matter of taste. -
Are Django caches syncronized, memcached etc
I have a scenario where a function will be called from two different places at the same time. before calling the function from each place, i'm using cache system to see if it's already been called by one of them. then after calling the method, i'm caching a value indicating that it has been called. using memcached. -
Django Contact form: TypeError: "to" argument must be a list or tuple
I am trying to get my email contact form to work on my Django website. I am getting an error in my browser as follows: Exception Type: TypeError Exception Value: "to" argument must be a list or tuple Exception Location: /home/Gassymule/Skeletonv3.1/myvenv/lib/python3.6/site-packages/django/core/mail/message.py in init, line 264 It specifically highlights try: send_mail(name, company, phone, subject, message, from_email, ['kkeeper.ch@gmail.com']) from my views.py but I am not entirely sure what it needs me to fix. The Tutorial website that I took this from used this exact format. views.py from django.http import HttpResponse from django.shortcuts import render, redirect from django.views.generic import TemplateView from website.forms import ContactForm from django.core.mail import send_mail, BadHeaderError def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] name = form.cleaned_data['name'] company = form.cleaned_data['company'] phone = form.cleaned_data['phone'] try: send_mail(name, company, phone, subject, message, from_email, ['kkeeper.ch@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('thanks') return render(request, "email.html", {'form': form}) def thanks(request): return HttpResponse('Thank you for your message.') Here is the relevant code from my contact form template. email.html <form action="" method="post"> {% csrf_token %} <ul class="contactList"> <li id="name" class="contact">{{ form.name }}</li> <li id="company" class="contact">{{ form.company }}</li> <li id="email" class="contact">{{ … -
CORS/Django/AWS/Elastic Load Balancer
I was running a Django server on Elastic Beanstalk for a few weeks --- a problem forced me to reinstantiate the instance. For some reason now, I can't seem to get my API to work correctly -- my requests are turning into: 504 (GATEWAY_TIMEOUT) I have the correct settings in my Django app and the thing was working correctly two hours ago. I'm fairly confident this is an AWS issue but I'm not sure where to go to fix it. -
Django model field _('name')?
I'm reading the django.contrib.auth.models.py file and I see this being done all over the place: name = models.CharField(_('name'), max_length=255) I believe 'name' is the option designating the name of the database column to use for this field. But what does surrounding it with _('...') mean? And what's the advantage to doing that? -
Send Activation Code in Email After Registration
As we seen in different website, After signup it sends 6/5 character of activation code in our email.And we use that activation code to activate our account. I am trying to do the same thing but cant figured out how to do it in django-rest-framework Currently, I am using Djoser for Registration and activation. Djoser sends activation url in the email and its working fine. How can i replace activation url by activation code of 6 alphanumeric character for account activation ?? Am Using: Django-Rest-Framework, Django-Rest-Fraework-JWT, Djoser -
Django rest framework viewset and url mixup
In my project, i have 2 different viewset of the different serializer as both get query is different than each other. However, after applying the routers, when i go to check the API output, both API were using the same url instead. I did double check to make sure both serializer and views are different but i still get the same result. Moreover, there is another url which i create with 2 different view thus 2 different router yet it work as i wanted. Did i do something wrong ? Here is the screenshot of the output to get better understanding of what im talking about. Its really weird : https://imgur.com/a/PVfcu As u can see from my code below, in the url i specify 2 different viewset for different url however, only the schedule works, the user and family url however, got problem. Here is my code: serializer class FamilySerializer(serializers.ModelSerializer): class Meta: model = Family fields = ('id', 'userId', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'relationship', 'birthTime', 'bmi', 'height', 'weight', 'bloodtype', 'allergy') class Family2Serializer(serializers.ModelSerializer): class Meta: model = Family fields = ('id', 'userId', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'relationship', 'birthTime', 'bmi', 'height', 'weight', 'bloodtype', 'allergy') class Schedule2Serializer(serializers.ModelSerializer): valid_time_formats = ['%H:%M', '%I:%M%p', … -
Basic Django app index pathing syntax error
So I'm just getting started with Django and I decided to go through a tutorial that is a tad outdated in terms of syntax so I was wondering if someone could show me where I'm going wrong here and maybe provide a solution with the updated syntax :) Thanks in advance!! I'm running python 3.6 and Django 2.0.1 :) Here is the link to the tutorial: https://www.youtube.com/watch?v=iZ5my3krEVM skip forward to 13:10 for the syntax in question. here is my code: from django.urls import path from . import views urlpatterns = { path('', views.index, name='index')] and here is my output: File "/home/jon/Py_Dev/venv/Django-Projects/mysite/webapp/urls.py", line 5 path('', views.index, name='index')] ^ SyntaxError: invalid syntax -
Steps to work with django-jet-demo
I am trying to see django-jet-demo in action, i.e. https://github.com/geex-arts/django-jet-demo, but It didn't work. git clone https://github.com/geex-arts/django-jet-demo.git mkvirtualenv venv cd django-jet-demo pip install -r requirements/base.txt django makemigrations I have the errors 1- configparser.NoSectionError: No section: 'common' If I remove config.get(..., 'common') inside application/settings.py 2- configparser.NoSectionError: No section: 'email' If I remove config.get(..., 'email') inside application/settings.py 3- If I remove config.get(..., 'database') inside application/settings.com How could I fix this problem? What are the steps to make django-jet-demo works? -
"Apps aren't loaded yet" when trying to run pytest-django
Using the (partial) polls app from the Django tutorial as an example, I'm trying to get pytest-django to run. Using the command django-admin startproject mysite2, I've created a project directory with the following structure: . ├── db.sqlite3 ├── manage.py ├── mysite2 │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── polls │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py └── pytest.ini My pytest.ini looks like [pytest] DJANGO_SETTINGS_MODULE = mysite2.settings python_files = tests.py test_*.py *_tests.py Following the tutorial, in polls/models.py I've created Question and Choice models: import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Now, if I make tests.py as described in the tutorial, which is based on Python's built-in unittest module, import datetime from django.utils import timezone from django.test import TestCase from .models import Question class QuestionModelTests(TestCase): def test_was_published_recently_with_future_question(self): time = timezone.now() + … -
Queryset in a while loop django
I'm using the queryset below and i'm quite new to Database's i want to know if it's not too much expensive to do so or if it is, suggest an alternative way? while active_user is None: active_user = Users.objects.filter(is_active=True).first() the is_active field is indexed in database (db_index=True) and the while loop won't take more than 2-3 mins. using MySql. -
Django 2.0 throws AttributeError: ''Image' object has no attribute 'replace'"
When trying to set an html image to my static path + image path in Django 2.0, the django development server displays the following error: Error during template rendering In template /Users/arikanevsky/webappgit/ari/templates/ari/software.html, error at line 5 'Image' object has no attribute 'replace' The Image class from models.py: class Image(models.Model): """This class contains a reference to the ImageField. It is part of a base of models comprising the webapp. """ uplpath = '%Y/%m/%d' dfltpath = 'page_images/Y/M/D/no_img.jpg' image = models.ImageField(upload_to=uplpath, default=dfltpath) def __str__(self): """Return human readable string of self.image.""" return self.image.name The index method from views.py: def index(request): page_list = get_list_or_404(Page.objects.all()) return render(request, 'ari/index.html', {'page_list': page_list}) The index.html file (it is used as named): {% if page_list %} <ul> {% for page in page_list %} <a href="/ari/{{page.id}}/bio"><p>My bio page</p></a> <a href="/ari/{{page.id}}/career"><p>My career page</p></a> <a href="/ari/{{page.id}}/software"><p>My software page</p></a> <a href="/ari/{{page.id}}/publications"><p>My publication page</p>. </a> {% endfor %} </ul> {% else %} <p>No pages are available :(</p> {% endif %} The software method from views.py: def software(request, page_id): software_page = get_object_or_404(Page, pk=page_id) return render(request, 'ari/software.html', {'software_page': software_page}) The software.html file: {% load static %} <img src = "{% static software_page.image %}" alt = "Profile Picture"/> The app directory structure is the following: (I believe we … -
Django multiple inner join?
I want to show in a html the name of the city, state and country of a publication. But they are in diferent tables. Here is my models.py class country (models.Model): country_name = models.CharField(max_length=200, null=True) country_subdomain = models.CharField(max_length=3, null=True) def __str__(self): return self.country_name class countrystate (models.Model): state_name = models.CharField(max_length=200, null=True) country = models.ForeignKey(country, on_delete=models.CASCADE, null=True) importance = models.IntegerField(null=True) def __str__(self): return self.state_name class city (models.Model): city_name = models.CharField(max_length=200, null=True) countrystate = models.ForeignKey(countrystate, on_delete=models.CASCADE, null=True) def __str__(self): return self.city_name class publication(models.Model): user = ForeignKey(users, on_delete=models.CASCADE, null=False) title= models.CharField(max_length=300, null=True) country=models.ForeignKey(country, on_delete=models.CASCADE, null=True) countrystate=models.ForeignKey(countrystate, on_delete=models.CASCADE, null=True) city=models.ForeignKey(city, on_delete=models.CASCADE, null=True) def __str__(self): return self.title And I want to show the country_name, countrystate_name and city_name in my HTML template. Here is my views.py def publications(request): mypublications = publication.objects.filter(user_id=request.session['account_id']) dic.update({"plist": mypublications }) return render(request, 'blog/mypublications.html', dic) and Here is my mypublications.html {% for pub in plist %} <div> <a href="{{ pub.id }}"> {{ pub.title }} </a> <p>{{ pub.county_name }}</p> HERE IS WHERE I WANT TO GET THE COUNTRY NAME, NOT THE COUNTRY ID <p>{{ pub.state_name }}</p> <p>{{ pub.city_name }}</p> </div> {% endfor %} but this not work. I put pub.country_id and it works but I want the name of the country. The same for state … -
React js and Django-rest-framework ( Getting request.user )
So i have created a django api view that maps to a url: http://127.0.0.1:8000/api/user/request/ to show the requst.user's username. However whenever i get this data from loadData in reactjs it sends back an empty string '', showing that there is no requested user/no user logged in. regardless if a user has logged in or not. BTW the django development server and react development server are separate, not sure if this matters? Reactjs class Wrapper extends Component { state = { requestUser: null } componentDidMount () { this.loadData() } loadData () { axios.get('http://127.0.0.1:8000/api/user/request/').then(response => { this.setState({ requestUser: response.data }); console.log(response.data) }) } } Django api view class RequestUserAPIView(APIView): def get(self, request, format=None): data = { "request_user": request.user.username } return Response(data) Url url(r'^user/request/$', RequestUserAPIView.as_view(), name='request_user'), -
django rest framework list DryPermissions
I have a django rest endpoint that returns a list and detail view. For the detail view I can use the function has_object_read_permission() in the model to check permissions. However, for the list view it is all or nothing as only has_read_permission() in the model is checked. I would like to limit the data in the entries without permissions in the list so it does not return more information than it should. For the individual entries in a rest endpoint list, the permissions can be checked and I can also include them in the entries if I include can be checked if I include permission_classes = (DRYPermissions,) in the viewset. My question is what is the best way to limit the entries without permission to yield something like this where the entries without permission have some fields deleted (or blanked) GET /rest/example/948/ HTTP 200 OK Allow: GET, PUT, PATCH, DELETE, OPTIONS Content-Type: application/json Vary: Accept { "id": 948, "permissions": { "read": true, "write": true }, name: "example 1", field1: 1, field2: 2, field3: 3, field4: 4, } { "id": 947, "permissions": { "read": false, "write": false }, name: "example 2", } would I modify them in the serializer or do … -
Have a UserProfile Objects, which then has a field that is a foreignkey to Team object. How to query the Team?
Here's what i'm trying to accomplish: I would like the page to show what the team object has thats related to that profile. Here are the models: class UserProfile(models.Model): owner = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) team = models.ForeignKey(Team, on_delete=models.CASCADE,) phone = models.CharField(max_length=11) class Team(models.Model): name = models.CharField(max_length=10) Here is the views.py: def userpage(request): """The home page""" profile = UserProfile.objects.filter(owner=request.user) team = Team.objects.get(------>?WHAT GOES HERE?<-----) context = { 'team': team, 'profile': profile } return render(request, 'app/userpage.html', context) Edit: Is this how I should even approach this? Or is the proper way to approach this is to just have the profile context and in the template access the team fields e.g. {{ profile.team.name }} -
Can't load template from an Angular route in a Django project
In my urls.py, I have the following patterns: url(r'^$', views.index, name='index'), url(r'^setup/$', views.index, name='index'), Both the patterns ultimately resolve to the same view, as the logic is handled in the Controllers. The view kinda looks like something like this: def index(request): return request(request, 'index.html', {}) In my index.html file, I load in Angular, my Angular App, the routes, and everything else. My angular routes look something like this: .when('/', { controller : 'BaseController', templateUrl : 'static/app_partials/base.html', reloadOnSearch: false }) .when('/products/', { controller : 'ProductsController', templateUrl : 'static/app_partials/products.html', reloadOnSearch: false }) Now, when I go to the first URL in my pattern, everything works nicely, and the route is able to load the template perfectly, as the url is http://example.com/static/app_partials/base.html, which is exactly where the file is. However, the second URL does not work, as the template being called now is http://example.com/setup/static/app_partials/base.html, which does not exist. How can I fix this issue? I have tried to put the whole URL in my routes, with the domain and stuff, but then I get a insecure URL error. Any help? Thanks. -
Loop Through Every Model In Django Project
In django, is there a way to loop through each model that is currently in your database? I would like to be able to have a function that gets the total number of rows in all of my models, per model, without having to the function every time I added a new model. the output being something like model1 rows: 23 model2 rows:234 and then if I were to add a new model it would automatically output model1 rows: 23 model2 rows:234 model3 rows:0 the ideal format would be something like. def getDbStatus() for m in Models: print(m.objects.count) -
How to annotate count of an already annotated value?
I have a model named Order with a timestamp_delivered (datetime field). Model Order is having a driver associated with it. I want to get number of days each driver has delivered orders. I am trying below query: Order.objects.annotate(date=Cast('timestamp_delivered'), DateField()).values('driver_id').annotate(days=Count('date')) but got the error: KeyError: date Tried running below command as well: Order.objects.values('driver_id').annotate(date=Cast('timestamp_delivered'), DateField()).annotate(days=Count('date')).values_list('driver_id', 'days') Got the output [(Driver1, 1), (Driver2, 1), (Driver2, 1)... ] Output I am expecting is something like in formar: [(Driver1, 2), (Driver2, 4), (Driver3, 8)... ] -
Redirecting users signing in with social accounts
I am using Django allauth for sign up and social authentication. For users signing up with there email, they are redirected normally to their profile based on their username as the slug. For example, something like this: views.py class RegisterView(SignupView): form_class = RegisterForm template_name = 'oauth/auth_form.html' def form_valid(self, form): return redirect('profiles:Index', slug=form.cleaned_data['username']) The user is redirected to the profiles app which contains an Index view that displays their profile based on the slug (their username inputted). This works correctly, however, when I try to do social sign in with Facebook or Google for example, it redirects me to /accounts/profile/# which is the default Django profiles page. I want them to be redirected to the profiles app, which is /profiles/{their username} How can I make this happen?