Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Disable Django Auth
I have two different Django Applications. Both the applications have there respective Auth. Applications are hosted on different servers. Now the use case is such that: There is a redirection link that can be provided from Application 1. Now i would want to disable auth on Application 2 when the link has been traversed from application 1 which already has a Single Sign on. To be noted, Each application can be access individually so i cannot disable auth on application2. How can this be achieved where Application 1 has a single sign on and when a link from application 1 is clicked, it gets redirected to application 2 but should not authentication that particular request as the request is from Application 1. Thank you. Arun. -
Django: Message App
I'm trying to create a messaging app. This is what I did so far. Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) Now I can filter the messages between request.user & any user but couldn't re-order the messages based upon the fact that if request.user sends someone a message the person whom he send a message his name should appear at the top or if some send a message to request.user his name should appear at the Top. As we see on social networks. This is what I tried, users = User.objects.filter(Q(sender__receiver=request.user) | Q(receiver__sender=request.user)).annotate(Max('receiver')).order_by('-receiver__max') This code is working fine only when request.user sends someone a message, whom request.user sends a message his name re-orders at the Top but It's not changing the ordering of messages in case if someone sends a message to request.user. I also tried, users = Message.objects.filter(sender=request.user, receiver=request.user).order_by("created_at") But, I could't filter out the distinct users. It's showing equal number of users as messages. What is the right way of doing this? Thank You -
How to make user interface that connects to back-end
I am in the process of building some machines/devices (you could think of them as kiosk like info devices with touchscreen and interface) I am thinking about what the best way would be to write the code for the machine but I just don’t have enough experience and there seems to be so many options. The underlying processes that have to be executed are now written in python (3.6). Python is not needed perse so I could also rewrite it in a different language. My idea for now was to make an GUI with PyQT or Tkinter and run that locally on the machines. The problem with that idea for now is that 1) the machines will be deployed so I need remote acces to it and 2) It seems to be not be the best solutions to use python for the GUI. What I would prefer would be to have a server running from my office to which the machines all connect to. The server should run the underlaying processes and probably create a response page on the machines (?). What would be needed for this? A server running ubuntu server and Django with python, css, js and html? … -
Azure Active directory authentication for custom web service api
My project structure is as- Web service api [not rest] implemented using django single page application implemented using angular 2 and HTML MongoDB as database I have deployed both spa as well as api on azure cloud. What I want to achieve is as- Secure and Authorize every request going to web api as there is no authorization implemented at api side. Single page application will be authenticated using saml which is to be implemented I am new to azure cloud and gone to lot of articles by microsoft as well as other blogs What I have tried- Registered web api in azure active directory Registered single page application in azure active directory Please guide me from here- As per my understanding- 1. Web api can be configured such that it only be accessible to single page application [ considering my scenario], hence no request can be directly access to web api service. please correct me if I am wrong I don't have any user except admin in azure active directory Considering above scenario kindly guide me for configuration. Any help will be much appreciated. Thanks in advance -
Django renders information to wrong database field
so I was implementing a database in Django to take in username and password using the given Users model. However, when I hit submit the password gets taken into the email field. Any suggestions on what I could be doing wrong? This is for user signup. Thank you! could it be that Users does not come with a passwords section? How would I Add that in? forms.py class UserRegistrationForm(forms.Form): username = forms.CharField( required = True, label = 'Username', max_length = 32 ) password = forms.CharField( required = True, label = 'Password', max_length = 32, widget = forms.PasswordInput() ) views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect from django import forms from .forms import UserRegistrationForm #from django.contrib.auth import views as auth_views #from . import views # Create your views here. def login(request): return render(request, 'login.html') def profiles(request): return render(request, 'profiles.html') def signup(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): userObj = form.cleaned_data print(userObj) username = userObj['username'] password = userObj['password'] if not (User.objects.filter(username=username).exists()): User.objects.create_user(username,password) user = authenticate(username = username, password = password) login(request) return HttpResponseRedirect('/') else: raise … -
How can I get the serializer-fields in APIView?
How can I get the serializer-fields in APIView? In the document, it only say how to add serializer-fields in serializers, but did not state how to get the serializer-fields in the APIView. I add so many serializer-fields in the CloudServerCreateSerializer: class CloudServerCreateSerializer(ModelSerializer): cpu = serializers.IntegerField() # eg:1,2,4, ram = serializers.IntegerField() # eg: 1,2,4, os = serializers.DictField() # eg: {"os_big":"Linux", "os_detail":"CentOS7.2"} disk_os = serializers.DictField() # {"disk_type":"SSD", "disk_size":"50"} disk_store = serializers.ListField() # [{"disk_type":"SSD", "disk_size":"50"}, {"disk_type":"SSD", "disk_size":"50"}] class Meta: model = CloudServer exclude = ['expiration_time'] but I do not know how to get these values in the views: class CloudServerCreateAPIView(CreateAPIView): serializer_class = CloudServerCreateSerializer permission_classes = [] queryset = CloudServer.objects.all() def post(self, request, *args, **kwargs): print(*args, **kwargs) #serializer.save() return Response(data="创建成功", status=HTTP_200_OK, exception=None) How to get the serializer-fields in rest framework views? -
print('urlpatterns: ', urlpatterns) returns nothing in URLconf
I am learning Django following Writing your first Django app, part 1 | Django documentation | Django I attach print statement to URLconf for debugging. from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), ] print('urlpatterns:', urlpatterns) The server did not respond even with None Quit the server with CONTROL-C. 12/Nov/2017 19:13:36] "GET /polls/ HTTP/1.1" 200 40 [12/Nov/2017 19:13:43] "GET /polls/ HTTP/1.1" 200 40 I checked several times to make sure no bugs existing within such mininal codes,The following is all the codes: #views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") Contract to it,print statement works in my other project. urlpatterns: [<RegexURLResolver <RegexURLPattern list> (admin:admin) ^admin/>, <RegexURLPattern home ^$>, <RegexURLPattern login ^login/$>] System check identified no issues (0 silenced). The browser functions normally to display the message ("Hello, world. You're at the polls index.") What's the problem? -
django - TypeError how to get instance of a foreignkey from the user instance
I am getting the following type error and its due to this instance in view. The model as you can see below where Employee is onetoone relation to User and Company is the foreignkey to the Employee. How would I be able to solve this by getting the instance of company ? Or what is the problem. companysetting_form = CompanySettingEdit(instance = request.user.employee.company) Below is the typeerror TypeError at /employee/companysettings/ __init__() got an unexpected keyword argument 'instance' Request Method: GET Request URL: http://127.0.0.1:8000/employee/companysettings/ Django Version: 1.11.7 Exception Type: TypeError Exception Value: __init__() got an unexpected keyword argument 'instance' Exception Location: /Users/megasap/Documents/project/railercom/railercomapp/views.py in employee_companysettings, line 83 Python Executable: /Users/megasap/Documents/project/myvirtualenv/railercom/bin/python Python Version: 3.6.3 Python Path: ['/Users/megasap/Documents/project/railercom', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Users/megasap/Documents/project/myvirtualenv/railercom/lib/python3.6/site-packages'] Below are my code: https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/views.py @login_required(login_url='/employee/sign-in/') def employee_companysettings(request): companysetting_form = CompanySettingEdit(instance = request.user.employee.company) <---- this is the problem if request.method == "POST": companysetting_form = CompanySettingEdit(request.POST, instance = request.user.employee.company) if employee_form.is_valid(): employee_form.save() return render(request, 'employee/account.html', { "companysetting_form":companysetting_form }) https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/forms.py class CompanySettingEdit(forms.Form): name = forms.CharField(max_length=50, required=False) tel = forms.CharField(max_length=50, required=False) address_1 = forms.CharField(max_length=50, required=False) address_2 = forms.CharField(max_length=50, required=False) address_zip = forms.CharField(max_length=50, required=False) address_city = forms.CharField(max_length=50, required=False) address_state = forms.CharField(max_length=50, required=False) address_country = forms.CharField(max_length=50, required=False) class Meta: model = Company fields = ("name", "tel", "address_1", "address_2", … -
List all objects and variables of a python program
Is there a way in Pycharm (or elsewhere) to list all objects and variables defined at runtime of a Python program? My use case is learning a third-party Django app. I'd like to see a list of all objects instantiated, and variables defined when the server is running. I do realize that most likely the list would be overwhelming. However, I believe it's a good way to start familiarizing oneself with a new project. -
django - cannot save password correctly in form
I am trying to have a form that allows the user to change password. Everytime I change the password, it cannot login. for example if password is "jake", I change to "jake1", I cant login with the password "jake1" or even "jake" Here is how the form looks like: https://imgur.com/a/MdPs0 https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/views.py @login_required(login_url='/employee/sign-in/') def employee_account(request): employee_form = EmployeeFormEdit(instance = request.user) if request.method == "POST": employee_form = EmployeeFormEdit(request.POST, instance = request.user) if employee_form.is_valid(): employee_form.save() return render(request, 'employee/account.html', { "employee_form":employee_form }) https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/forms.py class EmployeeFormEdit(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ("password",) https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/templates/employee/account.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form employee_form %} <button type="submit" class="btn btn-pink">Update</button> </form> https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py Its just using the standard User model class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) -
How to get more params when I use the rest framework?
How to get more params when I use the rest framework ? This is my model: class CloudServer(models.Model): buytime = models.ForeignKey(to=BuyTime) # 购买时长 expiration_time = models.DateTimeField() # 失效时间 availablearea = models.ForeignKey(to=AvailableArea) profile = models.TextField() # 简介 This is my serializers: class CloudServerCreateSerializer(ModelSerializer): class Meta: model = CloudServer fields = "__all__" This is my views: class CloudServerCreateAPIView(CreateAPIView): serializer_class = CloudServerCreateSerializer permission_classes = [] queryset = CloudServer.objects.all() def post(self, request, *args, **kwargs): # there I want more params. #serializer.save() return Response(data="创建成功", status=HTTP_200_OK, exception=None) The rest framework api web browser: You see, there are only 4 params related to the model fields. In there I want to get more params inputs here(such as 10 count), and when I create I want to save 4 of the 10 params to the model serializer, and the remainder 6 params to use as other usefulness in CloudServerCreateAPIView's post method. -
Django with multiple ManyToManyField form
This is my first Django app to prove to myself (and my company) that we should adopt Django, but so far it has proven tricky. I'm trying to create an app that shows all the employees of a company and for each, all the employee's many skills organized in categories. Here's my model: from django.db import models class Category(models.Model): name = models.CharField(max_length=64) def __str__(self): # __unicode__ on Python 2 return self.name class Skill(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=64) def __str__(self): # __unicode__ on Python 2 return self.name class Employee(models.Model): login = models.CharField(max_length=16) fullname = models.CharField(max_length=64) skills = models.ManyToManyField(Skill, through='EmployeeSkill') def __str__(self): # __unicode__ on Python 2 return self.fullname class EmployeeSkill(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) skill = models.ForeignKey(Skill, on_delete=models.CASCADE) LEVELS = ( ('0', 'None'), ('1', 'Very Basic Knowledge (hours)'), ('2', 'Basic Knowledge (days)'), ('3', 'Good Understanding Knowledge (weeks)'), ('4', 'Excellent Knowledge (months)'), ('5', 'Expert Knowledge (years)'), ) level = models.CharField(max_length=1, choices=LEVELS) desired_level = models.CharField(max_length=1, choices=LEVELS) def __str__(self): return "{} level of knowledge for {} is {} / desired is {}".format(self.employee.fullname, self.skill.name, self.level, self.desired_level) I'm able to create an Employee, a Skill and an EmployeeSkill, and even show all the employee skills for a given employee but where I'm struggling … -
Annotate objects in a queryset with next and previous object ids
How do I annotate the objects in a Django ORM queryset so that every items contain IDs of the the object before (previous) and the one after (next)? I am using PostgreSQL and Django 1.11. -
How can I set constant in Model CharField and used in Form
I am new for Python and Django, and now I try to use constant such as max_length_value for Model and want to be re-used in the Form, but get exception when debug. I googled and try the property usage, but failed. code list like below models.py def max_length_value(): return 128 class Category(models.Model): name = models.CharField(max_length=max_length_value, unique=True) and in the forms.py from .models import Category class CategoryForm(forms.ModelForm): name = models.CharField(max_length=max_length_value) Could anybody tell me how to solve this situation ? Thanks a lot!! -
ModuleNotFoundError: No module named 'newsletter.model' in my Django project
I started this Django project. Created an app called newsletter. This is my models.py: from django.db import models # Create your models here. class SignUp(models.Model): email = models.EmailField() full_name = models.CharField(max_length=120, blank=False, null=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.email This is my admin.py: from django.contrib import admin # Register your models here. from .forms import SignUpForm from .models import SignUp class SignUpAdmin(admin.ModelAdmin): list_display = ["__str__", "timestamp", "updated"] form = SignUpForm #class Meta: # model = SignUp admin.site.register(SignUp, SignUpAdmin) Then i opened a forms.py: from django import forms from .model import SignUp class SignUpForm(forms.ModelForm): class Meta: model = SignUp fields = ['email'] The problems is, when i tried to runserver, it gave me the error: File "C:\Users\JOSHUA\Documents\trydjango18\src\newsletter\admin.py", line 4, in <module> from .forms import SignUpForm File "C:\Users\JOSHUA\Documents\trydjango18\src\newsletter\forms.py", line 3, in <module> from .model import SignUp ModuleNotFoundError: No module named 'newsletter.model' Someone please help. -
Running Python Scripts in Pycharm While Working on Django Project
I am working on a Django project, using PyCharm as my IDE. In regular PyCharm projects, whenever I'm working on a certain function I am able to use the Run Function (Ctrl+Shift+F10)command to run that function. This is nice, since I can check the validity of approach as I go along. Now, in Django, I've got a separate functions.py file within one of my Apps as such Project\App\functions.py which contains some functions I'd like to use within that app. Whenever I attempt to execute a function from within that file, from that file in PyCharm, I get the following error: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Ok, so I go to Run->Edit Configurations->Python(on the left menu)->functions and on the Configuration tab, in the Environment->Environment Variables field, I add the following: DJANGO_SETTINGS_MODULE = MYPROJECT.settings Now, I get the following error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I'm not sure I know what that means, though after receiving the second error I feel like I'm either A.) Missing something obvious; or B.) Trying to do something ridiculous. I would like to know the best way to … -
Can't chain search query - django rest framework
I've included code for my urls, views, and filters .py files. Please let me know if I missed information. I can currently run a query like: http://127.0.0.1:8000/api/?min_age=50 I'd like to have the option to include as many search parameters as I'd like: http://127.0.0.1:8000/api/?min_age=20&?max_age=50&?month_min=10 I don't think this is possible after reading docs for django-filters, but it's possible with https://github.com/philipn/django-rest-framework-filters. The examples appear to deal mostly with joining columns from tables, and my information is on one table. Does anyone have example code that might set me in the right direction? views.py from rest_framework.generics import ListAPIView from .models import FullData from .serializers import FullDataSerializer from .filters import FullDataFilter from django_filters import rest_framework as filters class ListView(ListAPIView): serializer_class = FullDataSerializer queryset = FullData.objects.all() filter_backends = (filters.DjangoFilterBackend,) filter_class = FullDataFilter filters.py import rest_framework as filters from .models import FullData from django_filters import rest_framework as filters class FullDataFilter(filters.FilterSet): age = filters.NumberFilter() min_age = filters.NumberFilter(name='age', lookup_expr='gte') max_age = filters.NumberFilter(name='age', lookup_expr='lte') month = filters.NumberFilter() month_min = filters.NumberFilter(name='month', lookup_expr='gte') month_max = filters.NumberFilter(name='month', lookup_expr='lte') class Meta: model = FullData fields = ['age', 'month'] urls.py from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from .views import ListView urlpatterns = { url(r'api/$', ListView.as_view(), name="apiurl"), } urlpatterns = format_suffix_patterns(urlpatterns) -
Django wont run after connecting MySQL database
when I enter: python manage.py runserver into my usual folder I am given the following output: C:\Users\user\projects\steveone\steveone>python manage.py runserver Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line File "C:\Users\Kevin\Anaconda3\lib\site-packages\django__init__.py", line 3, in from django.utils.version import get_version File "C:\Users\user\Anaconda3\lib\site-packages\django\utils\version.py", line 5, in import subprocess File "C:\Python34\Lib\subprocess.py", line 395, in import threading File "C:\Python34\Lib\threading.py", line 10, in from traceback import format_exc as _format_exc File "C:\Python34\Lib\traceback.py", line 3, in import linecache File "C:\Python34\Lib\linecache.py", line 10, in import tokenize File "C:\Python34\Lib\tokenize.py", line 32, in import re File "C:\Python34\Lib\re.py", line 123, in import sre_compile File "C:\Python34\Lib\sre_compile.py", line 18, in assert _sre.MAGIC == MAGIC, "SRE module mismatch" AssertionError: SRE module mismatch I am not running a virtualenv (I know), and this only started happening after I connected LibreOffice to MySQL via JBDC today. From what I have gathered, I have a feeling that it might have to do with the path, but I am not really sure. I am fairly new to web development but up until this point I have been able to find answers to the problems that I have faced. I had it up and running yesterday and this has only happened since after I was fiddling … -
Django RawQuerySet not working as expected
I ran a raw query just as the Django docs point: Model.objects.raw('SELECT * FROM model') and I got this result, Why it only shows the object? <RawQuerySet: 'SELECT * FROM model'> -
Model field doesn't show up on admin site
Model field doesn't show up on admin site unless I specify it in ModelForm class in my forms.py file form.py class RegistrationForm(forms.ModelForm): class Meta: model = Registration fields = [ 'student_name', 'student_lastname'] For example: If I remove student_name from the fields list it will not appear on django admin site. Please help me out. -
How can I set up Django Crontab in Docker container?
I have added django-crontab to the requirements.txt and 'django_crontab' in INSTALLED_APPS. This file should add data to the PostgreSQL database however it doesn't work. Any ideas why? Maybe I should use Celery scheduler instead? I have in management/commands file myfile.py and I set it up in this way TIME_ZONE = 'UTC' CRONJOBS = [ ('21 22 * * *', 'django.core.management.call_command', ['myfile']), ] -
sqlite3 issues using UPDATE sql transaction (+ Django models?)
Not quite sure what I'm doing wrong here, but I'm sure it's something simple. I'm using the following method and passing in the following query, update_db("UPDATE ? SET views=? WHERE id=?", (table, value, post['id'])) to update my table. The update_db method takes in the sql query and arguments as follows: def update_db(sql, args): cur = get_db().execute(sql, args) The get_db method works as this is able to execute SELECT * FROM x queries without any trouble. I have the following fields in my model: views = models.IntegerField(default=0) So it's a declared integer value. Essentially this is set to the value returned (this will be set by a query to the Google Analytics API but this is neither here nor there). When running the query outlined at top I get the following error: File "test.py", line 66, in update_views update_db("UPDATE ? SET views=? WHERE id=?", (table, int(value), post['id'])) File "test.py", line 34, in update_db cur = get_db().execute(sql, args) sqlite3.OperationalError: near "?": syntax error Ok, so which "?" ...? And what the heck is wrong with the query string? -
Filter the items listed in a manytomany field in a Django view
I have a Django database that has schools, teachers, and classes. Teachers and classes have a ForeignKey relation to schools. Classes have a ManyToMany relation to teachers. When creating/adding new classes I want the ManyToMany list of teachers that is shown in the views form to be restricted to only show a list of the teachers that belong to the same school as the class (this is necessary to stop teachers from other schools being selected by mistake). I am using class based views. Is there a way to filter what is shown in the ManyToMany field of the form? -
How to add a button in email input?
I am trying to put a button inside an email input in a Django form. This is the code with the button next to the email input: <div class="container" id="notifyEmailFormContainer"> <form action="{% url "landing:notify_email_add" %}" method="post" id="notifyEmailForm"> {% csrf_token %} <div class="form-group row"> <div class="col-sm-10 input-group" id="emailInput"> <div class="input-group-addon" id="comingSoonEmailIcon"><i class="fa fa-envelope fa fa-2x" aria-hidden="true"></i></div> <input class="form-control" type="email" name="email" placeholder="Your email...." maxlength="255" required id="id_email"/> </div> <div class="col-sm-2"> <button type="button" class="btn btn-block btn-primary" onclick="addNotifyEmail()" id="submitNotifyEmail">Notify Me</button> </div> </div> </form> </div> I have a tried a couple answers in similar questions but it seems I can't get it to work. -
How to document function-based views parameters?
I'm developing a REST API with Django 1.11 and Django REST Framework 3.7. I installed Django REST Swagger 2.1 to generate the documentation. I'm using a function-based view like this: from rest_framework.decorators import api_view, permission_classes @api_view(['POST']) @permission_classes((permissions.AllowAny,)) def jwt_auth(request, provider, format=None): """ View description here """ pass As you can see, my view is recognized by Swagger and it has the correct description: "View description here". However: You can see the "Description" column is empty for the provider URL parameter. The POST parameters are not documented (obviously, because there is no way for Swagger to know them) How can I write documentation for the URL and POST parameters of a function-based view, as well as the responses? I tried YAML Docstrings but it seems it's for the old version (0.3.x) and it doesn't work with version 2.x.