Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Backend : Cant get objects attribute in Atom IDE
I am quite new to Django. I am using Atom IDE, in views.py of an patrticular app, whenever i try to access my model.objects, it doesnt really show any error but dosent autocomplete either. I have already installed autocomplete, autocomplete-python, and django-atom packages. Is there any way (or) package that i could install to make this autocomplete work? -
start project with django
I have pandas installed in my computer but I get this error enter image description here File "C:\Users\hp\AppData\Local\Programs\Python\Python36\dj\xaon\app\views.py", line 1, in import pandas as pd ModuleNotFoundError: No module named 'pandas' & also I have a problem to import views File "C:\Users\hp\AppData\Local\Programs\Python\Python36\dj\xaon\app\urls.py", line 2, in from . import views -
How to add pending tasks to lists
I am creating a todo list API(backend) in django rest framework. I have two models List and Task #models.py from django.db import models # Create your models here. class List(models.Model): list_name = models.CharField(max_length=200) def __str__(self): return self.list_name class Meta: db_table = 'list' class Task(models.Model): todo_list = models.ForeignKey(List, on_delete=models.CASCADE) task_name = models.CharField(max_length=500) due_date = models.DateField() done = models.BooleanField(default=False) def __str__(self): return self.task_name class Meta: db_table = 'task' The serializers file, #serializers.py from rest_framework import serializers from rest_framework_serializer_extensions.serializers import SerializerExtensionsMixin from .models import List, Task class ListSerializer(SerializerExtensionsMixin, serializers.ModelSerializer): class Meta: model = List fields = "__all__" class TaskSerializer(SerializerExtensionsMixin, serializers.ModelSerializer): class Meta: model = Task fields = "__all__" expandable_fields = dict( todolist=ListSerializer ) My todo list app will have multiple lists and each list have multiple tasks. Each task will have a due date and can be marked as done. I am trying to add the number of pending tasks to my List json. How do I go about doing that? -
Serve Django in specific path
Would it be possible to serve a django application in an specific path instead of the common root path? http://localhost:8000/mydjangoapp instead of http://localhost:8000 Could this be achieved just by tuning nginx or apache and gunicorn or it would be necessary to modify something in the django code itself? Thanks. -
Touch command kill uWSGI service
I'm getting a little issue with uWSGI and my Django application on production server. I have a FreeBSD jail which has only one Django application. When I made code improvements, I do a touch on settings file in order to take into account modifications. However, touch kills my uWSGI service each time. So I need to start uWSGI manually else I get a 502 Bad Gateway issue with my browser. Environment: Django version : 1.11.20 uWSGI version : 2.0.15 Python version : 3.6.2 uWSGI.ini file: This is my uwsgi.ini file : [uwsgi] pythonpath=/usr/local/www/app/src/web virtualenv = /usr/local/www/app/venv module=main.wsgi:application env = DJANGO_SETTINGS_MODULE=main.settings.prod env = no_proxy=*.toto.fr env = LANG=en_US.UTF-8 master=true processes=2 vaccum=true chmod-socket=660 chown-socket=www:www socket=/tmp/uwsgi.sock socket-timeout = 60 post-buffering = 8192 max-requests = 5000 buffer-size = 32768 offload-threads = 1 uid=www gid=www logdate=true log-maxsize = 20000000 manage-script-name=true touch-reload = /usr/local/www/app/src/web/main/settings/prod.py Issue: When I make a deployment, once it's done, I do : touch /usr/local/www/app/src/web/main/settings/prod.py Then I have my uWSGI service out. This is the last log I have : Thank you very much ! -
How to implement OAuth when the resource and auth servers are same and client and resource owner are same
I have a Django Rest API which is the backend for a Angular frontend. There are many clients who use the service with our frontend. Now some enterprise clients wanted to integrate the APIs from their systems. I wonder what is the best way to implement OAuth for this scenario. I am thinking Client Credentials grant type is the best way. Question1: Is client credentials the right approach here ? For those enterprise users, it is sufficient they get just access token through the UI interface so that they can access all our APIs. But here the problem is one additional step of getting the Client ID and Client Secret first and using that to get Access Token. Question 2: What is the use of client ID and client secret ? Question3: Should my backend hide the process of generating Client ID and Client secret and just give Access token (or) give them Client ID and Client Secret and ask then to generate access token ? TLDR; How to implement OAuth when the resource server and auth servers are same and client and resource owner are same -
Track django admin with Google Analytics
What is the fastest way to put all admin pages of a Django app under Google Analytics/TagManager? -
Trying to access image from postgresql
I need to store link to images in a PostgreSQL table and access it from web page developed in python. How can I do that? -
Combine Date and Time in Django Queryset
I am trying to combine date and time in my Django Queryset using annotate. TimesheetEntry.objects.exclude( timesheet_is_running = False ).filter( timesheet_users__userprofile__user_company=request.user.userprofile.user_company ).annotate( timesheet_clock_in_time_date=datetime.datetime.combine('timesheet_clock_in_date', 'timesheet_clock_in_time') ).values_list( 'timesheet_jobs__job_number', 'timesheet_clock_in_time_date', ) But it is giving me TypeError combine() argument 1 must be datetime.date, not str -
Django Rest Framework | Many To Many Intermediate Table with extra field
I researched a lot and looked at many examples. But could not find suitable answer. I would like to post my data like this: { "name" : "product 1", "materials" : [ { "id":1, // material id "rate" : 40 } ,{ "id":2, // material id "rate" : 60 } ] } models.py class Material(models.Model): name = models.CharField(max_length=120) class Product(models.Model): name = models.CharField(max_length=120) materials = models.ManyToManyField(Material, through='MaterialProduct') class MaterialProduct(models.Model): material = models.ForeignKey(Material, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) rate = models.FloatField(default=100) I would like to learn what is the best way/approach to serialize intermediate table. serializers.py class MaterialSerializer(serializers.ModelSerializer): class Meta: model = Material fields = '__all__' class MaterialProductSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField(source='material.id') name = serializers.ReadOnlyField(source='material.name') class Meta: model = MaterialProduct fields = ('id', 'name', 'rate') class ProductSerializer(serializers.ModelSerializer): materials = MaterialProductSerializer( many=True, source='materialproduct_set') class Meta: model = Product fields = ('id', 'name', 'materials') Also why django rest framework does not have any example on doc/api-guide I really wonder that. If I knew this problem I would contribute this. Thank you all for any help. -
Django template tag: getting key, value of dictionary
I want to access the key, value of below dictionary and output them into Django template file. However, I couldn't get the value. It raised an error. How to access each dictionary key, and its values (option_name, answer, img_option)? Dictionary {u'options': [{235: <OptionForm bound=False, valid=Unknown, fields=(option_name;answer;img_option)>}, {236: <OptionForm bound=False, valid=Unknown, fields=(option_name;answer;img_option)>}, {237: <OptionForm bound=False, valid=Unknown, fields=(option_name;answer;img_option)>}, {238: <OptionForm bound=False, valid=Unknown, fields=(option_name;answer;img_option)>}] } Django template {% for key, option in options.items %} <tr class="option_row rowRecord" id="{{key}}"> <td>{{option[0].option_name}}</td> <td>{{option[0].img_option}}</td> <td>{{option[0].answer}}</td> <td><i class="material-icons option-delete">delete</i></td> </tr> {% endfor %} ERROR Raised TemplateSyntaxError: Could not parse the remainder: '[0].option_name' from 'option[0].option_name' -
My User Update form is not showing up in my template
My User profile update form is not appearing in my template. I can only see 'Update' button and legend name. But I don't see the actual form. Here is my forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth import get_user_model from .models import Profile, Post, User # User = get_user_model() class UserCreationModelForm(UserCreationForm): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'country', 'city', 'email', 'password1', 'password2', 'access_challenge'] class UserUpdateForm(forms.ModelForm): username = forms.CharField() email = forms.EmailField() class Meta: model = User fields = ['username', 'email' ] Here is my views.py def profile(request): uform = UserUpdateForm() pform = ProfileUpdateForm() context = { 'uform': uform, 'pform': pform } return render(request, 'users/user_detail.html', context) Here is my urls.py from django.urls import path from .views import UserRegistrationView, CabinetView, PostCreateView, PostDetailView from . import views app_name = 'users' urlpatterns = [ path('accounts/register/', UserRegistrationView.as_view(), name='register'), path('accounts/cabinet/', CabinetView.as_view(), name='cabinet'), path('accounts/cabinet/', views.profile, name='profile'), path('accounts/cabinet/blog/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('accounts/cabinet/new/', PostCreateView.as_view(), name='post-create'), path('', views.home, name='home'), path('accounts/cabinet/blog/', views.blog, name='blog'), path('accounts/cabinet/countries/', views.countries, name='countries'), path('accounts/cabinet/cities/<int:pk>/', views.cities, name='cities'), path('accounts/cabinet/address/<int:pk>/', views.address, name='address'), And here is my user_detail.html template <form method="post" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Profile Info</legend> {{ uform }} {{ pform }} </fieldset> <div class="form-group"> <button class="btn btn-info btn-block" … -
post request gives 403 forbidden django ajax
i've a register form and a function to post the values to django via ajax, but for some reasons, the post request says 403 forbidden but the get request does the job. I want to use post request in this functionality but it doesn't seem to work, tried putting {% csrf_form %} too within the template, but still it says 403 Forbidden. Any sugessstion? Views.py from django.http import HttpResponse from django.shortcuts import render from django.views import View class signUp(View): def post(self, request): return HttpResponse(" POST method successfull !!") Urls.py path('insert/', views.signUp.as_view()), HTML Form: {% extends 'base.html' %} {% block title %} <title> Register </title> {% endblock %} {% block content %} <div class="row breadcrumb_nav"> <div class="col-md-1" ></div> <div class="col-md-10" style="margin-bottom: 35px;"> <!-- START col-md-12 Section --> <ol class="breadcrumb nm" > <li><a href="login.php"> Home </a></li> <li class="active"> Register </li> </ol> <div id="quickViewPage_error_container"> <div id="animated_image"></div> <div id="results_container"></div> </div> </div> <!--end of col-md-12 --> <div class="col-md-1" ></div> </div> <!-- end of row --> <!--start of row --> <div class="row"> <div class="col-md-1" ></div> <div class="col-md-12"> <!-- START Right Section --> <div class="main_shadow panel panel-default"> <!-- START OF panel panel-default--> <div class="panel-body panel-body-padding"> <!-- -START OF PANE --> <div class="modal-header"> <h4 class="modal-title" id="exampleModalLabel"> Register </h4> … -
Django - Assign Foreign Key upon Form submission
Hi I just started learning Django this week and am creating a to do list application, where a user can create multiple to-do lists, each list able to hold multiple items. Models.py class Todolist(models.Model): listname = models.CharField(max_length=200) date = models.DateTimeField(default=datetime.now) user = models.ForeignKey(User, default=None, on_delete=models.CASCADE) class Todo(models.Model): todoname = models.CharField(max_length=200) date = models.DateTimeField(default=datetime.now) user = models.ForeignKey(User, default=None, on_delete=models.CASCADE) whichlist = models.ForeignKey(Todolist, on_delete=models.CASCADE, null=True) Views.py def dolist(request, list_id): tdlist = Todolist.objects.get(id=list_id) current_user = request.user user_todo = Todo.objects.filter(user=current_user, whichlist=tdlist) return render(request, 'todolist/tdlists.html', {'tdlist': tdlist, 'todos': user_todo}) def addtodo(request): if request.method == 'POST': user = request.user list_id = request.POST.get('list_id') Todo.objects.create(todoname = request.POST['todoname'], user=user, whichlist=list_id) .HTML Template form <form action="/index/todolist/addtodo" method="POST"> {% csrf_token %} <input type="hidden" name="list_id" value={{list_id}}> <input type="text" name="todoname"/> <input type="submit" value="Add to-do item"/> </form> Right now, if I take out whichlist parameter in Todo.objects.create(), the to do item is able to be created upon form submission but the foreign key is not assigned so it won't show up on that todo list page. I can go to the Django admin site and manually assign whichlist for the Todo item, and it will then show up on that list page. How can I make it so that the todo item's foreignkey is … -
How to use Django login functionality using already created MySQL database table?
I have Database Student, in that database I have one table Student_login whose structure is : Student_id ---Integer Student_Username-----Varchar Student_password-----Varchar Now I have to use already present database for Django Login Functionality but Django creates its own table for login instead of it I want to use Student_login table for login and it encrypts password but I don't want to encrypt the password cause some other people are also using same table. How to achieve this? Thanks in Advance -
How can I add Linkedin login to my website using Django allauth?
I am using frontend React Js and Backend Django. I need to setup login with LinkedIn and Facebook. So I am trying to achieve by using django allauth. I am new to Django so I am confusing the how to setup. Can I use allauth to achieve my requirements or what can be the best way to achieve and how? -
How to get the pk parameter in return redirect
I have a view: @login_required def add_auditor(request, pk, pk2): company_details = get_object_or_404(Company, pk=pk) user_profile = get_object_or_404(Profile, pk=pk2) company_details.auditor.add(user_profile.name) company_details.save() return redirect(reverse('company:search_auditors' , pk=company_details.pk)) The redirect url in this view is not working as it has a primary key parameter in it. How to pass a primary key parameter in redirect url? Any idea -
Django data storage - SQL or something else?
I am building a Django web app which will essentially serve static data to the users. By static, I mean that admins will be able to upload new datasets but no data entries will be made by users. Effectively, once the data is uploaded, it will be read-only on request by a user. Given that these are quite large datasets (200k+ rows), I figured that SQL would be the best way to store the data - this avoids reading large datasets into memory (as you'd have to with a pickle or json?). This has the added bonus of using Django models to access the data. However, I am not sure of the best way to do this, or if there is a better alternative to SQL. I currently have an admin page that allows you to upload .xlsx files which are then parsed and added as model entries row-by-row. It takes FOREVER (30+ minutes for 100K rows). Perhaps I should be creating a whole new db outside of Django and then importing that somehow, but I can't find much documentation on how this could/should be done. Any ideas would be greatly appreciated! Thanks in advance for any wisdom. -
Subquery many-to-many relation in Django 1.9
I have such models: class Genre(models.Model): name = models.TextField(null=True, blank=True) min_age = models.IntegerField(default=0) max_age = models.IntegerField(default=0) objects = GenreManager() class Meta: get_latest_by = 'id' class Book(models.Model): name = models.TextField(null=True, blank=True) genres = models.ManyToManyField(Genre, related_name='genres') suggested_age = models.IntegerField(default=0) objects = BookManager() and I want to query it in such way: there can be duplicates (when min/max age changes, new object will be saved to db), but I want to get the latest one, so I come up with: class GenreManager(models.Manager): def get_latest_genre_obj(self, genre): return self.get_queryset().filter(name=genre).latest() to be able to retrieve one. Now, I want to get books, using Genre object from above - I need min and max age values in my query. I've tried something like this: class BookManager(models.Manager): def get_books_from_genre(self, genre): genre = Genre.objects.get_latest_genre_obj(genre) return self.get_queryset().annotate(actual_genre=genre).filter(actual_genre__min_age__gte=F('suggested_age'), actual_genre__max_age__lte=F('suggested_age')) But it looks like I cannot annotate object to other object: AttributeError: 'Genre' object has no attribute 'resolve_expression' So, how to query it like I want to? I thought about Subquery() as I thought it can help me, but it's Django 1.11 feature andI'm using 1.9 version. To sum up what I want to achieve: from genres, retrieve newest (with highest id) object with particular name and use it's fields while querying … -
Custom Manager not always adding calculated field for many-to-one relationship
I am using Django 2.1 for a project. One of my Models (called Event in the example below) has a many-to-one relationship to another Model (Thing in the example below). The first model should have what I think is a calculated field. To illustrate: class Thing(models.Model): ... class Event(models.Model): ... thing = models.ForeignKey(Thing, on_delete=models.CASCADE) ts = models.DateTimeField(default=django.utils.timezone.now) _delta = timedelta() ... objects = EventManager() @property def delta(self): return self._delta @delta.setter def delta(self, value): self._delta = value An Event should have a calculated field (a timedelta called delta) that shows how much after the previous event it happened. Because an Event's time can change, it seems better to calculate this timedelta at run time instead of storing it in the database (keeping the deltas up to date in the database gets hairy, for example if an event's time changes in a way that changes the sequence of events, i.e. one event "jumps" over another one). So I have a custom manager for Event's class EventManager(models.Manager): def get_queryset(self): qs = super().get_queryset() for r in qs: r.delta = django.utils.timezone.now() - r.ts # fake calculation return qs When I now "use" this, for example in a template {% for event in thing.event_set.all|dictsortreversed:"ts" %} or … -
Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings'
I'm having issues with running my django app with mod_wsgi. Here's the log message [wsgi:info] [pid 21407] mod_wsgi (pid=21407): Python home /var/www/myproject/myenv. [wsgi:info] [pid 21407] mod_wsgi (pid=21407): Initializing Python. Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' Upon checking other issues in SO and on the github page of mod_wsgi, the fix for this is to make the config point to the environment. At this point, I'm sure that I am pointing the python home setting to the correct environment path I also executed sys.prefix and it does point to /var/www/myproject/myenv I'm also sure that I used the correct python version to build mod_wsgi and create the virtualenv for my project. I was able to run pip install -r requirements.txt as well. Here's my config file LoadModule wsgi_module /usr/lib64/httpd/modules/mod_wsgi.so WSGIRestrictEmbedded On WSGIPythonHome /var/www/myproject/myenv WSGIScriptAlias / /var/www/myproject/myproject/wsgi.py process-group=sgcdjango.com WSGIDaemonProcess sgcdjango.com python-home=/var/www/myproject/myenv WSGIProcessGroup myapp.com WSGIApplicationGroup %{GLOBAL} <Directory /var/www/myproject/myapp/> <Files wsgi.py> Allow from all Require all granted </Files> </Directory> Alias /static/ /var/www/myproject/static/ <Directory /var/www/myproject/static> Require all granted </Directory> -
return status from server before finals results
I am building a server side with Django on python 2.7 I am trying to create an Ajax request from the HTML page, that will be a long script in the file views.py, so I want that during that, it will also report a status before finals results. The only thing I know is to return a final results to the Ajax request through the views.py file -
How to create a strategy to book a product for a small advance payment or buy the same product with full amount?
I have a question on django-oscar's pricing for a product, in my project I have a set of products. What I want is each product in two pricing, one for booking the product before hand by paying a small amount of money or buying the whole product by paying full money. So we will have a book button to book the product selected for a small amount of money (add product to cart for this amount) or add the product to cart for the whole price. I am using Django==2.1.7 and django-oscar==1.6.7 How to implement this in the best way? -
Rebuild Model file from migrations
I had a complete models.py file. Unfortunately, some of my model class has been deleted. But I did migration before this incident happened. My Question is, Is it possible to rebuild the models.py from last migrations? Or I have to rewrite the model classes. -
Which version of django i should use?
I am going to start new large scale project in Django with DRF(Django Rest Framework), but i am confused to choose version i should pick, 1.11 or 2.1, suggestions please.