Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display the DateTimeField stored in IST in db in IST itself given the condition that USE_TZ=True?
So, I am a novice in Django and have set my timezone as 'Asia/Kolkata' and USE_TZ=True in the settings file. For the datetime that is stored in UTC in the database, the display is in my current timezone. However, for the datetime that is stored in IST in the db, the admin is adding +5:30 for display(i.e. it assumes the values in db are in UTC) I want to find a way to manually tell those models/admin that USE_TZ=False for them. I tried extending the DateTimeField and overriding the function get_internal_type to return CharField and not DateTime. It is working fine as well. However, I do not understand how it actually is working in the background. class MyDateTimeField(DateTimeField): def get_internal_type(self): return "CharField" class FileUpload(models.Model): .... .... created_at = models.MyDateTimeField(auto_now_add=True) updated_at = models.MyDateTimeField(auto_now=True) Also, for the long run, I am a bit wary about the model level changes and want to know if anything else can solve this problem. -
Django inline form validation based on sibling records
I have Admin model which has inline model with its form e.g class ParentAdmin(admin.Model): inlines = (ChildInline,) class ChildInline(admin.TabularInline): .. form = ChildInlineForm .. class ChildInlineForm(forms.ModelForm): def clean(self): .... My clean() method logic is not coming along because of my business logic. I need to validated all inline objects as a set and some might depend on each other, so I need all posted inline objects before validation. E.g an instance of child C is only validated or expected when child A is in the set. Since form is dirty and value might be in the db or not. I need to intercept all the child instances before validation (e.g clean is called on any of the instance) and pass the set to validation function e.g class ChildInlineForm(forms.ModelForm): def clean(self): self.instance.parentobj.__dirtychildren=#desired logic self.instance.validate(self.instance.parentobj) I looked at admin model code, I dont see any suitable way to add this functionality. Not in save_formset , save_related, etc. The example code I put is hypothetical as the actual code very complex to cut-and-past -
How to upgrade sqlite 3.8.2 to >= 3.8.3
In a virtual Env with Python 3.7.2, I am trying to run django's python manage.py startap myapp and I get this error: raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2). I'm running Ubuntu Trusty 14.04 Server. How do I upgrade or update my sqlite version to >=3.8.3? I ran $ apt list --installed | grep sqlite libaprutil1-dbd-sqlite3/trusty,now 1.5.3-1 amd64 [installed,automatic] libdbd-sqlite3/trusty,now 0.9.0-2ubuntu2 amd64 [installed] libsqlite3-0/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed] libsqlite3-dev/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed] python-pysqlite2/trusty,now 2.6.3-3 amd64 [installed] python-pysqlite2-dbg/trusty,now 2.6.3-3 amd64 [installed] sqlite3/trusty-updates,trusty-security,now 3.8.2-1ubuntu2.2 amd64 [installed] and sudo apt install --only-upgrade libsqlite3-0 Reading package lists... Done Building dependency tree Reading state information... Done libsqlite3-0 is already the newest version. 0 upgraded, 0 newly installed, 0 to remove and 14 not upgraded. -
Make html+css layot for posts
I want to make page layot for imageboard. I am new at css and tried different solutions none of them works as I want. There should be post with pictures float to the left and text that wraps arount it. Sound pretty simple but I can't accomplish it. I've tried to make container "post" where will be 3 of children container in their order: postHeader (which should be on top), pic (with picture) and text (with text post). I've tried to set pic and text display:inline-block; to make them align in one line but without text with property there draw one under each other. I tried set float: left on pic to make picture float left and make word wrap around it but then if text is too few there is no container. I dont want to use sizes, it breaks responsivness. How it should look -
How can I prevent the fields in inlines to reference the latest created object in Django Admin
I have a model PlacedOrder that is referenced by other models using OneToOneField and ForeignKey. So I am using StackedTabularInline to render it on my PlacedOrderAdmin model. The weird behavior is that when I start my django application I can create a new PlacedOrder object with no problems but after that when I try to create another object the fields on the inlines are already filled with the content from the object that I just created and I can't create a new object no matter what I try, it keeps showing me the error "Please correct the errors below." Only the fields that belongs to the inlines does that, the fields from the model PlacedOrder are "clean". If I restart django I can see all the objects created and their data seems correct. part of the Models: class PlacedOrder(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4(), editable=False ) ... total = models.DecimalField( _('total'), max_digits=8, decimal_places=2 ) class OrderStatus(models.Model): placed_order = models.OneToOneField( PlacedOrder, on_delete=models.CASCADE ) status = models.CharField( _('status'), choices=STATUS_CHOICES, max_length=30, ) Here is one of the inlines: class OrderStatusInline(nested_admin.NestedTabularInline): model = app_models.OrderStatus and the Order @admin.register(app_models.PlacedOrder) class OrderAdmin(nested_admin.NestedModelAdmin): inlines = (OrderStatusInline, OrderPaymentInline, OrderDeliveryInline, SelectedProductInline, ) -
How to fix the the error in migration when migrating in mysql in django
When I'm trying to migrate my models in Django in MySQL. I always got this error "django.db.utils.ProgrammingError: unsupported operand type(s) for %: 'bytes' and 'tuple'". Im feeling it was version conflict on mysql and django Attached is the error message I'm getting -
Overriding __str__ allows string passed in foreign key field Django
I have a form in Django that allows a lecturer to select units that have been created in the db. When the dropdown menu is clicked, it shows something like Unit object (ICT270) that is why I override the Unit model str function to return self.code and self.code is the primary key of the Unit model. Apparently, after I do this, everytime I need to fill in the foreign key field to the Unit model, I can just pass in a string instead of the Unit object itself. Passing a Unit object works as well. for example, Class.objects.filter(unit_id='ICT270').first(). In the past, I need to pass a Unit object, not a string. I am a bit worried about this, I feel vulnerable if I can pass a string like that. Do you think this is an unexpected behavior or perfectly safe if the str includes all primary keys of that model? thank you -
react is not displaying anything in after setting react-router-dom in react-django app
I have made a Django api and now I want to connect it with reactjs for that I used this tutorial react-django to setup both of them together. after all setup, it was working fine but when I added react-router-dom It displays nothing on the screen but shows something like this in the console GET http://localhost:8000/favicon.ico 404 (Not Found) How can I solve this? This is how I setup my routes see the code import React from 'react'; import ReactDOM from 'react-dom'; import LoginPage from './pages/LoginPage'; import HomePage from './pages/HomePage'; import { BrowserRouter, Route } from 'react-router-dom'; const App = () => <div> <Route exact path="/" component={HomePage} /> <Route path="/login" component={LoginPage}/> </div> ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter> , document.getElementById('app')) -
Django sessions expiring despite calling set_expiry(0)
I'm trying to implement a "remember me" checkbox into django's builtin LoginView, as suggested on this question, but even though I call set_expiry(0), the sessions still expire after SESSION_COOKIE_AGE, regardless of the cookie expire date (which is correctly set to 1969). I'm using django 2.1.7 with python 3.7.2, and the only session-related settings on my settings.py is SESSION_COOKIE_AGE, which is set to 5 seconds for resting purposes. Django seems to use a database backend as default. I'm using sqlite for development. This is my view class: class UserLoginView(LoginView): form_class = registration.UserLoginForm def form_valid(self, form): remember = form.data.get('remember_me', False) if remember: self.request.session.set_expiry(0) return super(UserLoginView, self).form_valid(form) And this is the original LoginView form_valid method (being overriden above) class LoginView(SuccessURLAllowedHostsMixin, FormView): ... def form_valid(self, form): """Security check complete. Log the user in.""" auth_login(self.request, form.get_user()) return HttpResponseRedirect(self.get_success_url()) ... As you noticed, I'm using a custom form_class. A very simple override of the default form: class UserLoginForm(AuthenticationForm): remember_me = BooleanField(required=False) If I use a debugger right after the set_expiry call, I can see that the sesion expiry age is still the default 5 seconds: > /project/app/views/accounts.py(64)form_valid() -> return super(UserLoginView, self).form_valid(form) (Pdb) self.request.session.get_expiry_age() 5 I get similar results if I let the request complete and redirect, … -
How can I filter uuid as text with Django?
How can I filter uuid as text with Django? For example, I wanted to do like below. Group.objects.filter(id__startswith='000') Do I need to use extra? -
Syntax for Disabling all form fields in Django
I'm trying to display a user's profile on a project. I'd like to render a form but make it disabled/unable to be changed (just displayed). I can't figure out the syntax for it. Help would be appreciated! Here's the view.py: @login_required def profile(request): user_form = UserForm(instance=request.user) user_form.fields.disabled = True <------- HELP HERE return render(request, 'rentadevapp/profile.html', {'user_form': user_form}) I essentially want to just display a readonly/disabled form. User then has an edit button that takes them to a profile edit page. Thanks for the help! Here's the html just in case: <form method="GET" action="/profile_edit">{% csrf_token %} {{ user_form|crispy }} <button type="submit" class="edit btn btn-default btn-block btn-lg">Edit</button><br> </form> -
Getting Data from accordion menu in view.py dynamically
I have an Accordion menu in my site which it has category, subcategory and the article, I want to be able to see which category, subcategory and article the user has clicked and filter my model based on those conditions, being article in subcategory in category. I first tried to put the links of accordion inside a form and named each link, but that just messed up how it showed on screen. any suggestion or alternative route to get what I want is also appreciated, all I want is to be able to filter my database, based on 3 conditions, conditions being the category, subcategory and the article which are the hierarchical steps in the accordion menu. Thanks -
Full Calendar Dropping Event Objects After Data Transform
I am having a strange issue with full calendar. I am trying to create a mouseover for different types of events and have had some issues with attributes of an event object disappearing between the "eventDataTransform" and "eventMouseover" functions This is for a web application that will be loading data from an API to populate full calendar. I am able to get all of the object's attributes when I do not perform a transformation on the event. I am inspecting the object and show that it is present when the object is transformed and not so when it is moused over. calendar = $("#k_calendar").fullCalendar({ isRTL : KUtil.isRTL(), header : { left : "prev,next today", center : "title", right : "month" }, editable : false, eventLimit : false, navLinks : true, weekends: true, eventSources: [ // Loaded from a previous source data, "{% url 'pentesting-api:pentest-events' %}" ], displayEventTime: false, // Where the error is eventDataTransform: function (eventData) { if (eventData.hasOwnProperty('vendor')) { eventData.end = moment(eventData.end).add(1, 'days').format(); eventData.title = eventData.full_name; eventData.backgroundColor = statusColors[eventData.status]; eventData.allDay = true; return eventData; } else { eventData.title = eventData.event_name; eventData.backgroundColor = eventColors[eventData.event_type]; // all attributes are on the object here console.log(eventData); return eventData; } // Using the below … -
The current path, myapp/home, didn't match any of these
I want to run a project in pycharm with framwork django but i get this error when I click on a new page I used python 36 Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/myapp/home Using the URLconf defined in xaon.urls, Django tried these URL patterns, in this order: ^admin/ ^ ^$ [name='home'] ^ ^fileupload/ [name='app_file_upload'] ^analyze/ ^forecast/ ^media\/(?P<path>.*)$ The current path, myapp/home, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. ``` -
Most efficient way to create a snapshot of a django queryset?
I’m new to Django, and I need to clean up all existing objects meeting a certain set of criteria that were previously created by an importer before the importer re-runs. I'm trying to figure out the most efficient way to do this. Currently I'm getting the existing objects before importing the new objects and updating them with a boolean to_be_deleted=True: Thing.objects.filter(source=importer).update(to_be_deleted=True) import_new_things(source=importer) Thing.objects.filter(to_be_deleted=True).delete() But do I really need to run update on that entire queryset? Is there a way to just save a snapshot of the queryset to a variable and then delete those after the importer finishes? -
Error when creating django project in pycharm
I am a beginner in python and pycharm, I want to create a Django project under pycharm and for that I followed the steps in this link:https://medium.com/@srijan.pydev_21998/configure-pycharm-for-python-django-and-introduction-to-django-rest-framework-f9c1a7cb4ba0 But when I run manage.py I had the following errors: E:\first_app\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm 191.6014.12\helpers\pydev\pydevconsole.py" --mode=client --port=50395 import sys; print('Python %s on %s' % (sys.version, sys.platform)) import django; print('Django %s' % django.get_version()) sys.path.extend(['E:\\first_app', 'C:\\Program Files\\JetBrains\\PyCharm 191.6014.12\\helpers\\pycharm', 'C:\\Program Files\\JetBrains\\PyCharm 191.6014.12\\helpers\\pydev']) if 'setup' in dir(django): django.setup() import django_manage_shell; django_manage_shell.run("E:/first_app") PyDev console: starting. Python 3.7.1 (default, Dec 10 2018, 22:54:23) [MSC v.1915 64 bit (AMD64)] on win32 Django 2.2 Traceback (most recent call last): File "<input>", line 6, in <module> File "E:\first_app\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "E:\first_app\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "E:\first_app\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\hanan\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "E:\first_app\venv\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Program Files\JetBrains\PyCharm 191.6014.12\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, … -
Django-DataTables-View Many-to-Many Fields
How would this example for django-datatables-view: http://django-datatable-view.appspot.com/many-to-many-fields/ be changed to the current syntax to allow for many-to-many fields? Ideally, how would it show the string representation of the field rather than just one field? Old Example: class ManyToManyFields(DatatableView): model = Entry datatable_options = { 'columns': [ 'id', 'headline', ("Authors", 'authors__name', 'get_author_names'), ("Authors", 'authors__name', 'get_author_names_as_links'), ], } def get_author_names(self, instance, *args, **kwargs): return ", ".join([author.name for author in instance.authors.all()]) def get_author_names_as_links(self, instance, *args, **kwargs): from datatableview import helpers return ", ".join([helpers.link_to_model(author) for author in instance.authors.all()]) -
django-mptt different data ordering on two machines with same code and data
I'm using django-mptt library for creating directory hierarchy like this: directory_a directory_some_name directory_a directory_b directory_some_name directory_b directory_some_name directory_some_name models.py class BaseDirectory(MPTTModel): name = models.CharField(_('Name'), max_length=120) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', verbose_name=_('parent directory')) def __str__(self): return self.name def clean(self): # some cleaning super().clean() def save(self, *args, **kwargs): self.clean() super().save(*args, **kwargs) class MPTTMeta: order_insertion_by = ['name'] class Meta: abstract = True class OtherDirectory(BaseDirectory): # directory model from another application class Meta: verbose_name = _('directory') verbose_name_plural = _('directories') I deployed this code to server and it works fine(all items inserting in alphabetic order, if i change it somehow and run OtherDirectory.objects.rebuild() it returns back to normal alphabetic order. But locally on my machine alphabetic ordering didn't work. It's randomly puts new element into parent tree. I'am tried to download database backup from my server and restore it locally, but if i run OtherDirectory.objects.rebuild() data again shuffled in wrong order. After some researching of django-mptt sources and debugging my app i found out this queryset in django mptt contains different data between my local machine and server with same db data and code, filters and order_by: queryset = node.__class__._tree_manager.db_manager( node._state.db).filter(filters).order_by(*order_by) And now i'm stuck. Why this can be? local machine: OS X … -
Implementing django-tables2 with jinja2
I'm making a django project but switched from the standard template to jinja2. I used to be able to load django-tables2 like this: {% load render_table from django_tables2 %} But since load isn't a tag I can use with jinja2, I can't use that anymore. Here is my jinja2 file: def environment(**options): env = Environment(extensions=['jinja2.ext.i18n', 'jinja2.ext.with_'], **options) env.globals.update({ 'static': static, 'url': reverse, }) return env What do I need to write in order to properly implement django-tables2 into jinja2? -
django rest model permissions
I'm using Django 2.1 and djangorestframework 3.9.2. I wish to be able to control access to REST operations on Django model objects via the Django admin interface, ideally using user permissions. For example, only users who have read permissions on model object Foo should be able to see Foo in my REST API. I read the docs and it seems maybe I could use DjangoModelPermissions or DjangoObjectPermissions. However, when I clear all user permissions in the DB, and set DEFAULT_PERMISSIONS_CLASS to either DjangoModelPermissions or DjangoObjectPermissions, I am still able to see things in the REST API. That means lack of permissions is not preventing me from seeing objects as I hoped. Example settings: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.DjangoModelPermissions', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), } Suggestions? -
TRAVIS CI : ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
I have created a sample project [Django/Python] in a private repo on GitHub. Recently, I have a added a sample .travis.yml file to it in order to get CI rolling. Now issue is my tests [I am using Pytest suite] pass when I run the command pytest on my local machine. But I am unable to get my test suite running on Travis because of the above mentioned error. Any help in this regard will be appreciated. Here's my sample .travis.yml file. language: python sudo: false python: - '3.6.4' services: - mysql addons: apt: sources: - mysql-5.7-trusty packages: - mysql-server cache: directories: - $HOME/.cache/pip before_install: - sudo mysql -e "use mysql; update user set password=PASSWORD('123123') where User='root';FLUSH PRIVILEGES;" - sudo service mysql restart before_cache: - rm -f $HOME/.cache/pip/log/debug.log install: - pip install -r requirements/development.txt before_script: - sudo mysql -e 'CREATE DATABASE my_database;' script: - flake8 - pytest --cov -v --tb=native notifications: email: on_success: change # [always|never|change] on_failure: always # [always|never|change] Just to add one more piece of info. My DB settings are as follows : settings.py. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_database', 'USER': 'root', 'PASSWORD': '123123', 'HOST': 'localhost', # Or an IP Address that your DB is … -
How to save my entry through a UserChangeForm?
I created a UserChangeForm to edit the teacher information. When I submit the form, it didn't save the entry to the database. I need two users for two custom views, but the userchangeform is not saving subject to the teacher's table. Meanwhile, the usercreationform had no issue at all. models.py class User(AbstractUser): users = ( ('student', 'Student'), ('teacher', 'Teacher'), ) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user.user_type = "teacher" id = models.AutoField(unique=True, primary_key=True) subject = models.CharField(max_length=20) #return the doctors' name def __str__(self): return str(self.user) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: if instance.user_type == "student": Student.objects.create(user=instance) elif instance.user_type == "teacher": Teacher.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) forms.py class TeacherForm(UserChangeForm): class Meta: model = Teacher fields = ('subject',) views.py def Edit_Teacher(request): if request.method == 'POST': form = TeacherForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('index') else: form = TeacherForm(request.POST, instance=request.user) args = {'form':form} return render(request, 'registration/edit_teacher.html', args) -
Can't get forms to render in Django
I'm working on a project and I don't get the django forms to render on any of my pages. I've compared it to django girls code, as that is what I usually consult but it looks virtually identical to it. It's not just this page, my other pages have issues with rendering the forms as well. Here's the code: Views.py from django.shortcuts import render from .models import * from .forms import * from django.shortcuts import render, get_object_or_404 from django.shortcuts import redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.db.models import Sum from django.utils import timezone from django.views.decorators.http import require_POST from .cart import Cart from django.db import transaction from django.contrib import messages @login_required def post_edit(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm(instance=Post) return render(request, 'rentadevapp/post_edit.html', {'rentadevapp': post_edit}, {'form': form}) Forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'text',) post_edit.html {% extends 'rentadevapp/base.html' %} {% load staticfiles %} {% load crispy_forms_tags %} {% block content %} <head> <link rel="stylesheet" href="{% static 'css/post_edit.css' %}"> </head> <body> <div class="container"><br> <h2>New Post</h2><br> <form method="POST" class="post-form">{% csrf_token … -
Send json data from browser to Django view with ajax POST
I am using handsontable to simulate a spreadsheet on my web application. I want to send the json data that the user enters into the spreadsheet to my database. Html button: <button id="send_post" class="btn size-medium bg-green text-white shadow hover-moveup">Send Post Request</button> Js: document.getElementById("send_post").addEventListener("click", function(event) { $.ajax({ url: 'http://127.0.0.1:8000/', type: "POST", dataType: "json", data: JSON.stringify(hot.getSourceData()), statusCode: { 200: function (your_Response_Data) { console.log(JSON.stringify(hot.getSourceData())) }, // ... handle errors if required 404: function () { } }, complete: function (jqXHR, textStatus) { } }); }) views.py @csrf_exempt @login_required(login_url='/login/') def index(request): user_id = request.user if request.is_ajax(): if request.method == "POST": received_json_data = json.loads(request.body) return HttpResponse(received_json_data, content_type="application/json") When I press the button, console.log is successfully logging the json to the console, but it is not getting to my django view -
Freeform text inside DRF_YASG generated docs
Is there a way to add freeform text to docs generated through drf_yasg? I can't see an obvious explanation in their docs. I just want to add a few sections of introduction text.