Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
django-taggit - use added tags
I am trying to get the django-taggit incoporated into my code. Must mention, I am an infant when it comes to Django framework. What I am looking to do is, when a user creats a post, he/she also adds tags to it ( in the long run I am hopint that these will be populated by suggested pre-defined tags. django-taggit is well added to the admin side of the project. I am having a very hard time to implement the user side. The error: AttributeError at /posts/create/ 'Post' object has no attribute 'save_m2m' Request Method: POST Request URL: http://127.0.0.1:8000/posts/create/ Django Version: 1.11.6 Exception Type: AttributeError Exception Value: 'Post' object has no attribute 'save_m2m' Exception Location: C:\Users\internit\Dropbox\Python\codepython\codepython\posts\views.py in create, line 26 Python Executable: C:\Users\internit\Dropbox\Python\codepython\env\Scripts\python.exe Python Version: 3.6.2 Python Path: ['C:\Users\internit\Dropbox\Python\codepython\codepython', 'C:\Users\internit\Dropbox\Python\codepython\env\Scripts\python36.zip', 'C:\Users\internit\Dropbox\Python\codepython\env\DLLs', 'C:\Users\internit\Dropbox\Python\codepython\env\lib', 'C:\Users\internit\Dropbox\Python\codepython\env\Scripts', 'c:\program files (x86)\python36-32\Lib', 'c:\program files (x86)\python36-32\DLLs', 'C:\Users\internit\Dropbox\Python\codepython\env', 'C:\Users\internit\Dropbox\Python\codepython\env\lib\site-packages'] Server time: Sun, 12 Nov 2017 21:50:26 +0000 Views.py @login_required(login_url='/accounts/login/') def create(request): if request.method == 'POST': if request.POST['title']:#check that the title and the url is included in the request post=Post() post.title= request.POST['title'] post.author= request.user post.pub_date=timezone.datetime.now() post.assignment_body = request.POST['assignment_body'] post.solution_body = request.POST['solution_body'] post.solution_comment = request.POST['solution_comment'] post.tags = request.POST['tags'] post.save() post.save_m2m() return redirect('home') else: return render(request, 'posts/create.html', {'error':'ERROR: Title and URL … -
KeyError when using Django Sessions in deployed application
I am trying to check if there is a logged in user on the home page of my Django app with the following code in my views: def index(request): my_user = request.session.get('currentUser') if my_user: this_user = User.objects.filter(email = request.session['currentUser'])[0] userSearchs = Search.objects.filter(userlist =this_user) context = { 'userMessage' : "Welcome " + request.session['currentUser'], 'userSearch' : userSearchs } else: context = { 'message' : 'Want to save your search history? Click here to login.' } return render(request,'main/index.html',context) I have no issue with program when I run it locally but my deployed version displays a keyError every time new users navigate to the home page. You can check out the exact error by visiting the deployed app here http://54.190.44.1/ If the user logs in and then logs out the error no longer displays and the site functions as expected. Here is my login function in my views: def login(request): response = User.objects.login_user(request.POST) request.session['error'] = False if not response['status']: for error in response['error']: messages.error(request, error) request.session['error'] = True return redirect('login/loginPage') request.session['currentUser']=response['user'][0].email return redirect('/') And here is the logout function: def logout(request): request.session['currentUser'] = '' return redirect('/') I am currently at a loss on where to go from here and would appreciate any suggestions. Thanks! -
In Django Admin, Can I Specify for A New Foreign Key to be Automatically Added When Using a Text Area vs. the Default Dropdown?
I've got two models in my Django app's models: app/models.py class Source(models.Model) name = models.CharField(max_length=255, unique=True) class Relationship(models.Model) first = models.ForeignKey(Source, related_name='first') second = models.ForeignKey(Source, related_name='second') In my app/admin.py I have as follows: # Register Source admin.site.register(Source) # Define Admin View class RelationshipAdmin(admin.ModelAdmin): raw_id_fields = ('source', 'destination') # Register Relationship, Admin View admin.site.register(Relationship, RelationshipAdmin) This creates the classes and registers them in the Django admin, and the raw_id_fields = ('source', 'destination') line is replacing the default dropdown menu for attributes using a ForeignKey within the model. I'm doing this for preference of workflow. I'd like the following functionality to be achieved: When adding a value into one of the Relationship text areas within the Django admin, for that value to be automatically adding to the Source ForeignKey table if the value is unique (like the + button does in the default dropdown). However, Django obviously needs me to tell it I want this done—and I have no idea how to do that. Currently, when I add a value into the text area I've created I get the following error: Select a valid choice. That choice is not one of the available choices. This is clearly indicating that values entered into … -
2 ajax calls at the same time causing issues in views
I'm using django-el-pagination to render 2 querysets (Post and Comment) with ajax. So when I click more posts or more comments, it loads the next batch of objects in the respective queryset. Here is the JS function showing this: $('body').on('click', '.endless_more', function() { console.log($(this).html()); var user_queryset; if ($(this).html() === 'more posts') { console.log('POSTS'); user_queryset = 'user_posts' } else if ($(this).html() === 'more user comments') { user_queryset = 'user_comments'; console.log('COMMENTS'); } else { console.log('none'); } $.ajax({ type: 'GET', url: window.location.href, data: { 'user_queryset': user_queryset } }) }); and here is the view which receives the data from the function (user_posts or user_comments depending on what was clicked). def profile(request, user, extra_context=None): ... page_template = 'profile/profile.html' print('LOAD') if request.is_ajax(): print('Requests:', request.GET) user_queryset = request.GET.get('user_queryset') print('Queryset:', user_queryset) if user_queryset == 'user_posts': page_template = 'profile/user_posts.html' elif user_queryset == 'user_comments': page_template = 'profile/user_comments.html' elif user_queryset == 'user_inbox': page_template = 'profile/user_inbox.html' else: pass else: pass print('Template:', page_template) context = {'user_posts': user_posts, 'user_comments': user_comments, 'page_template': page_template} return render(request, page_template, context) Now, the JS works fine - it sends the correct data depending on what was clicked. So the page_template in the view is successfully updated during the ajax call, however it renders the parent template (profile.html) instead … -
Development Server won't render HTML image
I'm creating a web application using Django in IntelliJ. My HTML file wants an image but somehow my development server will not show the image at all. If I'm directly opening the HTML file and not using the server, I can see the image. I somehow feel it's an IntelliJ issue. I marked the folder as resources root and tried a bunch of things: creating an images folder at the root level and marking the folder as resources root, putting the image in same folder as HTML file; nothing works. HTML Code: {% extends 'base.html' %} {% block head %} <title>Page</title> {% endblock %} {% block body %} <br><br><br> <center><img src="1.png" height="200" width="200"></center> {% endblock %} Project Structure Please help! -
Django - redirect to a view after edit
I have a view that allows me to edit/update a post. The post is the result of filling out a form. This is similar I'm guessing to redirecting to a CMS post after editing. Here's the post view: class PostUpdateView(UpdateView): model = Product form_class = ProductForm template_name = 'edit_product.html' def form_valid(self, form): self.object = form.save(commit=False) self.object.save() return redirect ('products') @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(PostUpdateView, self).dispatch(request, *args, **kwargs) After updating the details in the form it redirects to the 'product' page, whereas I want to redirect to the item just edited. The URL for the items is: url(r'^([0-9]+)/$', views.detail, name = 'detail'), Each post is then a number in the url, such as http://127.0.0.1:8000/13/. I can redirect to the previous page, but takes me back to the edit view, whereas, I want to go back to the actual post view, showing the edit. Hopefully this isn't clear as mud. I get the sense I need to grap the orginating url, then use it once the form is updated so I'm researching that right now. Any guidance gratefully received. -
Why is my makemigrations not creating table
I know this question has been asked before ,but not resolved .When ever i run django makemigrations and migrate, it does not create a my table in the data base .I have done research but yet, do not understand why this is happening and how i can resolve it .Any one has faced such a problem before and resolved it .Please share your solution thanks in davance -
Error in adding django-axes to project
I have installed django axes with this command in cmd : pip install django-axes Then i addes to my setting.py file this parts : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'post_app', 'axes', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', 'axes.middleware.FailedLoginMiddleware', ] AXES_LOCK_OUT_AT_FAILURE = False AXES_USE_USER_AGENT = True AXES_COOLOFF_TIME = 1 AXES_LOGIN_FAILURE_LIMIT = 50 Now i want to runserver with this command : python manage.py runserver But i have this error in cmd : Unhandled exception in thread started by <function wrapper at 0x0000000004AA4908> Traceback (most recent call last): File "D:\python\data\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "D:\python\data\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "D:\python\data\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "D:\python\data\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "D:\python\data\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "D:\python\data\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.ready() File "D:\python\data\lib\site-packages\axes\apps.py", line 9, in ready from axes.decorators import watch_login File "D:\python\data\lib\site-packages\axes\decorators.py", line 3, in <module> from socket import inet_pton, AF_INET6, error ImportError: cannot import name inet_pton Is there any mistake?or any missed work?