Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Jinja templating engine filters
The jinja filter "replace" isn't working... not even recognized as a jinja valid filter. I am using django.. what should I do. {{ post.article | safe | replace("<script", "lt;") }} what am I missing error come up template syntax error Invalid filter: 'replace' -
Will Google Analytics Work with no js script and only cookies
I have a django website which already has google analytics intgrated. Recently I implemented the cookie consent from user manually. Will the analytics work if I exclude the script(based on consent) from the html and cookies already exists in the users browser ? -
Django: Class and first method which will always be called
I have a Class and as the first action, I want to erase all data in my database. I now wonder if I should insert this code below in __init__ or in __new__. I'm still a bit confused what's the best approach there. models = [ReservedItem, Billing, OrderItem, Order, Ticket, TicketTax, Event, Team, Organizer, User] for model_name in models: model_name.objects.all().delete() print("Deleted ", model_name) -
Python, Django, Javascript, HTML5, CSS3 and Bootstrap Interaction
I have created a website with Python, Django, Javascript, HTML5, CSS3 and Bootstrap. I want to know how these individual technologies interact with each other during a request or response in an E2E perspective.(Expecting an answer involving Django's MVT architecture)? -
Django passing Matlpotlib image as variable
I am trying to display a Matplotlib graph image as a variable in the .html but am unsuccessful. Im new to Django, any help would be greatly appreciated. I get this image when I go to the html page from django.shortcuts import render import sys import platform import datetime as dt from datetime import timedelta, date from django.shortcuts import render from django.http import HttpResponse from pylab import * import io inside views.py def submit(request): x = [1, 2, 3, 4, 5, 6] y = [5, 2, 6, 8, 2, 7] plot(x, y, linewidth=2) xlabel('x-axis') ylabel('yaxis') title('sample graph') grid(True) buf = io.BytesIO() plt.savefig(buf, format='png') plt.close() plt_bytes = buf.getvalue() buf.close() return render(request, 'jobs_app/index.html', {'path': plt_bytes}) inside index.html < img src="{{ path }}"> -
How to set logger class universally in Django App
I have a logger that just adds log_line if none is provided when calling logger.debug class UrlLogger(logging.Logger): def _log(self, level, msg, args, exc_info=None, extra=None): if extra is None: extra = {'log_line':' '} super(UrlLogger, self)._log(level, msg, args, exc_info, extra) I have about 20 different modules that I need to go into and add logging.setLoggerClass(UrlLogger) How can I set this as default in the settings? My settings currently look like this: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(name)s %(asctime)s %(module)s %(process)d %(thread)d %(pathname)s@%(lineno)s: %(message)s' }, 'simple': { 'format': '[%(levelname)8s] [%(asctime)s] %(module)10s/%(filename)s:%(log_line)s - %(message)s', 'datefmt': '%d-%m-%Y %H:%M:%S' }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': LOG_LEVEL, 'formatter': 'simple' }, }, 'loggers': { '': { 'level': LOG_LEVEL, 'handlers': ['console'], 'class': ['UrlLogger'], }, As you can see, I tried setting it here, but I don't think that's working because I am still getting errors. Message: 'Not Found: %s' Arguments: ('/tool_job_list/1/1fa119372de6/job/check/jexecution/report',) --- Logging error --- Traceback (most recent call last): File "/usr/local/lib/python3.6/logging/__init__.py", line 992, in emit msg = self.format(record) File "/usr/local/lib/python3.6/logging/__init__.py", line 838, in format return fmt.format(record) File "/usr/local/lib/python3.6/logging/__init__.py", line 578, in format s = self.formatMessage(record) File "/usr/local/lib/python3.6/logging/__init__.py", line 547, in formatMessage return self._style.format(record) File "/usr/local/lib/python3.6/logging/__init__.py", line 391, … -
app can't be installed in Django virtual environment
I used pip install django-celeryand pip3 install django-celery in Pycharm. After that I use import djcelery,but Pycharm reminds me no module named djcelery. Then I used pip list I can see django-celery 3.2.2 in the list. But when I went to virtual environment path myenv/lib/site-packages where I can see all the module or app that I have installed such as django-pure-pagination.But I can't find django-celery there. Any friend has any idea, how to fix it? -
Django Migration Version inside management command
I have a long running background process that processes data for a django web app. This process is created as a management command that runs in the context of the application. What I'm seeing is that in some cases, a migration is applied while a process is running from the same code base on another server. What happens is that we get errors in the data when a migration is applied while this process [or processes] is running. What I'm trying to do is identify the database migration version from this function and check for changes before each write step. If it is different, I can either abort or restart the process. I'm not sure how to access this information from django. I'm currently on Django 1.10 -
Django template and jquery
$( "#target" ).click(function() { var x = document.getElementById("myanchor").href; }); <div><a href="{{ audio.get_api_url }}" ><i class="icon-control-play i-2x" id="target"></i></a> </div> I need to send the api url to the my jquery function to call the ajax function to execute the code further. The page should not redirect to the api url, I cant figure this thing out. -
AttributeError: 'Settings' object has no attribute 'USE_MYSQL_COMMENTS'
I am following official Django documentation of 'Getting started with Django' https://docs.djangoproject.com/en/1.7/intro/tutorial01/ When I run the 'python manage.py migrate' command I get the following error: Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/init.py", line 385, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/init.py", line 377, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **options.dict) File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 67, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 17, in init self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 48, in init self.build_graph() File "/usr/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 183, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 59, in applied_migrations self.ensure_schema() File "/usr/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 49, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.get_table_list(self.connection.cursor()): File "/usr/local/lib/python2.7/site-packages/django/db/backends/init.py", line 173, in cursor if settings.USE_MYSQL_COMMENTS: File "/usr/local/lib/python2.7/site-packages/django/conf/init.py", line 47, in getattr return getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'USE_MYSQL_COMMENTS' Can anyone help. I am using Django version 1.7 and python 2.7. -
Getting descendents of objects in Django
I'd like to write a method that returns all descendents (i.e. children, grandchildren, great-grandchildren ...) of an object as a QuerySet. I wrote two methods, the first one (get_all_children) can return children and grandchildren but gives the following error if there are great-grandchildren (or lower-descendants): django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNION (SELECT DISTINCT `deneme_app_person`.`id`, `deneme_app_person`.`name`, `de' at line 1") The second method (get_all_children_list) works just fine (as far as I tested) but possibly slower and last line does not look good. models.py from django.db import models # Create your models here. class Person(models.Model): name = models.CharField(max_length=100) parent = models.ForeignKey( 'self', null=True, blank=True, related_name='children', on_delete=models.CASCADE) def get_all_children(self): """ This method will return all children and grandchildren of Person objects :return: """ p_list = self.children.all() if p_list.count(): for p in p_list: children = p.get_all_children() if children.count(): p_list = p_list.union(children) return p_list.distinct() def get_all_children_list(self): p_list = self.children.all() if p_list.count(): for p in p_list: children = p.get_all_children_list() if children.count(): p_list = set(p_list).union(children) # p_list = list(set(p_list + children)) return Person.objects.filter(id__in=[p.id for p in p_list]) # return list(p_list) def __str__(self): return f"({self.id}) - … -
Mysql data replication from local system to cloud derver
I have a scenario where i have to deploy my web application in 20 different stores across the world,since the internet connectivity is not good the application should work even if the internet is not available hence i decided to deploy the application on a local server on 20 stores individually. Now i need to integrate/Synchornization/Replicate all the data in the local database of 20 different store in to one single to cloud database. I am using Python (Django)and Vuejs(Front End) and mysql as my database to store the data. How can we achieve this -
Can't figure out why django variables aren't passed into template
I've been working on this for a few hours and for the life me of I can't get a variable from my django app into a template. html: {% block content %} {{test}} {% endblock content %} views: def home(request): context = {'test' : "test"} return render(request, "/dbus/templates/index.html", context) urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.home, name = 'home') ] (note: I left the imports out of the view code sample I provided) -
Dynamic field for Model in Django Rest Framework
(Using Django 2.0, Python 3.6, and Django Rest Framework 3.8) I'm trying to create an appointment scheduling API where Client can schedule a session with UserB based on UserB's availability. UserB has a field which displays their availability in the UserB model (in addition to other fields). When the Client tries to schedule an appointment, they are directed to a model with the following structure: class BookAppointment(models.Model): User_to_schedule_with = models.OneToOneField(Users) AvailableUserTimes_to_choose_from = (THIS IS WHER I'M STUCK) where the User_to_schedule_with field will be a dropdown which displays various Users the Client can schedule an appointment with (ex: UserB, UserC, UserD, etc.). After the Client has selected a User, I want the field AvailableUserTimes_to_choose_from to populate with the availability specific to the selected User. How would I be able to accomplish this, and how would I be able to access the one specific field AvailableUserTimes from the UserB model? Any help is greatly appreciated. -
No module named django.core.management on different computer
I am trying to run my server using python manage.py runserver on a new computer (Mac). The command worked on the previous computer (Windows), however now it yields an ImportError: No module named django.core.management The old computer was using python 3 and this new computer is using python 2.7.10. I believe this could be an issue but don't want to install python 3 on the new computer unless I have to because it is not mine. If this is the problem what are the steps I should do to resolve it? -
Celery Beat 4.2 not pulling from Django DB, always calling PersistentStore
With: CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' configured, running celery -A app beat -l info correctly starts and returns scheduler -> django_celery_beat.schedulers.DatabaseScheduler Celery beat correctly notices when the Periodic Task table changes however none of the tasks ever run. (I'm running a worker in a separate process) I noticed that even with the DB scheduler set I was getting a celerybeat-schedule.db file which made me wonder if Celery.beat was reading the right database. Dropping to the console: from celery.beat import Service test = Service(current_app).get_scheduler() print(test) <celery.beat.PersistentScheduler object at 0x10abec090> test.get_schedule() {u'celery.backend_cleanup': <ScheduleEntry: celery.backend_cleanup celery.backend_cleanup() <crontab: 0 4 * * * (m/h/d/dM/MY)>} Seems it's calling the celerybeat-schedule.db file with the automatically setup backend_cleanup task. Celery Beat is correctly monitoring the tasks that I add via the Django Admin, but the part of beat that actual reads and sends them to a worker only reads the celerybeat-schedule.db file which contains the automatically created clean up task. -
how to populate django model with a foreign key from a csv
my model.py: # Riders models ---------------------------------------- class CategoryTeam(models.Model): name = models.CharField(max_length = 256) def __str__(self): return self.name class Teams(models.Model): name = models.CharField(max_length = 256) code = models.CharField(max_length = 10) nation = models.CharField(max_length = 10) continent = models.CharField(max_length = 10) category = models.ForeignKey(CategoryTeam, on_delete=models.CASCADE,) def __str__(self): return self.name #-----------------------------------------------------# my script to populate from basic_app.models import CategoryTeam,Teams def populateCat(): f = open('CategoryCSV.csv') reader = csv.reader(f) next(reader) for row in reader: # Create new User Entry category = CategoryTeam.objects.get_or_create(name=row[0])[0] def populateTeamat(): f = open('FantaDS Project - Teams.csv') reader = csv.reader(f) next(reader) for row in reader: # Create new User Entry team = Teams.objects.get_or_create( name = row[0], code = row[1], nation = row[2], continent = row[3], #category = row[4] )[0] if __name__ == '__main__': print("Populating the databases Cat...Please Wait") populateCat() print('Populating Complete') print("Populating the databases Team...Please Wait") populateTeamat() print('Populating Complete') the exeption generated: File "C:\Users\Wynt\AppData\Local\conda\conda\envs\DjangoEnv\lib\site-packages\django\db\backends\utils.py",line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Wynt\AppData\Local\conda\conda\envs\DjangoEnv\lib\site-packages\django\db\utils.py", line 89, in __exit__raise ndj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Wynt\AppData\Local\conda\conda\envs\DjangoEnv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Wynt\AppData\Local\conda\conda\envs\DjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py",line 303, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: basic_app_teams.category_id -
Django invalid literal for int() with base 10: '??????? ???????' when i try to migrate
I'm trying to create a new tables in a new app added to my project .. makemigrations worked great but migrate is not working .. here is my models models.py from django.db import models # Create your models here. from fostania_web_app.models import UserModel class Tag(models.Model): tag_name = models.CharField(max_length=250) def __str__(self): return self.tag_name class BlogPost(models.Model): post_title = models.CharField(max_length=250) post_message = models.CharField(max_length=2000) post_author = models.ForeignKey(UserModel, on_delete=models.PROTECT) post_image = models.ImageField(upload_to='documents/%Y/%m/%d', null=False, blank=False) post_tag = models.ForeignKey(Tag, on_delete=models.PROTECT) post_created_at = models.DateTimeField(auto_now=True) when i try to do python manage.py migrate i get this error invalid literal for int() with base 10: '??????? ???????' -
Why does Django only emulate ON DELETE CASCADE?
I recently learned that Django's on_delete=CASCADE only emulates ON DELETE CASCADE -- if I run a DELETE FROM ParentTable as explicit SQL, it will fail when the child table's rows have live foreign keys to the parent. Why is Django designed this way? Why does it reproduce this behaviour in the Python layer when it could more easily add ON DELETE CASCADE to the table in the database itself? -
Django-ORM: Count number of groups of each user
I know that I can get the number of groups each user has with this query: User.objects.filter(groups__in=Group.objects.all()).annotate(Count('pk')) But something is missing: The users which are in no group at all. How can I use the django orm to get all users annotated by their group count, incluse users with no group? -
ValueError at /feedback/by/XXX/new Cannot assign "<SimpleLazyObject: <User: XXX>>": "Model.user" must be a "User" instance
I am trying to build this feedback application for the students to give feedback to their teachers. I am getting the following error when I try to create an instance of the feedback form. Please help. Thanks. Error: ValueError at /feedback/by/XXX/new Cannot assign "<SimpleLazyObject: <User: XXX>>": "Feedback.user" must be a "User" instance. CreateView: class CreateFeedback(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): form_class = FeedbackForm model = models.Feedback def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) Form: class FeedbackForm(forms.ModelForm): class Meta: fields = ("teacher", "subject", "param1", "param2", "param3", "param4", "param5", "param6", "param7", "param8", "param9", "param10") model = models.Feedback Path in urls.py: path('by/<username>/new',views.CreateFeedback.as_view(),name='create'), Models.py: class Feedback(models.Model): user = models.ForeignKey(User, related_name = 'feedback', on_delete=models.CASCADE, blank=False, null=False) teacher = models.ForeignKey(Teacher, related_name = 'feedback', on_delete=models.CASCADE, blank=False, null=False) subject = models.ForeignKey(Subject, related_name = 'feedback', on_delete=models.CASCADE, blank=False, null=False) param1 = models.PositiveIntegerField(blank=False, null=False) param2 = models.PositiveIntegerField(blank=False, null=False) param3 = models.PositiveIntegerField(blank=False, null=False) param4 = models.PositiveIntegerField(blank=False, null=False) param5 = models.PositiveIntegerField(blank=False, null=False) param6 = models.PositiveIntegerField(blank=False, null=False) param7 = models.PositiveIntegerField(blank=False, null=False) param8 = models.PositiveIntegerField(blank=False, null=False) param9 = models.PositiveIntegerField(blank=False, null=False) param10 = models.PositiveIntegerField(blank=False, null=False) def get_absolute_url(self): return reverse( "feedback:detail", kwargs={"username": self.user.username, "pk": self.pk}) def __str__(self): return (self.username + "->" + self.teacher) class Meta: ordering = ["teacher"] unique_together = ["user", "teacher", "subject"] class User(auth.models.User, … -
Django-ORM: distinct is needed. Why?
I am playing around with django ORM import django django.setup() from django.contrib.auth.models import User, Group from django.db.models import Count # All users print(User.objects.all().count()) # --> 742 # Should be: All users which are in a group. # But the result is different. I don't understand this. print(User.objects.filter(groups__in=Group.objects.all()).count()) # --> 1731 # All users which are in a group. # distinct needed print(User.objects.filter(groups__in=Group.objects.all()).distinct().count()) # --> 543 # All users which are in a group. Without distinct, annotate seems to do this. print(User.objects.filter(groups__in=Group.objects.all()).annotate(Count('pk')).count()) # --> 543 # All users which are in no group print(User.objects.filter(groups__isnull=True).count()) # --> 199 # 199 + 543 = 742 (nice) I don't understand the second query which returns 1731. I know that I can use distinct(). Nevertheless 1731 looks like a bug to me. What is the reason why below query is not distinct/unique? User.objects.filter(groups__in=Group.objects.all()) -
React production error with service worker: invalid MIME type
I have a React app that works in development and in production, however in production I get the following error in the console: The script has an unsupported MIME type ('text/html'). Failed to load resource: net::ERR_INSECURE_RESPONSE registerServiceWorker.js:80 Error during service worker registration: DOMException: Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html'). The error does not happen in development, only in the production environment. The app still works correctly in production, however I would still prefer to sort out the error. After doing some digging, it seems that in production the service-worker.js file is requested from the original index.html file while has a MIME type of text/html, the service-worker.js file therefore does not have the correct MIME type which would need to be application/javascript. Unfortunately even though I think I understand what the issue is, I haven't been able to fix it. The production build was created using create-react-app and is served up by a Django backend. The index.html page containing the React app is served up as follows: re_path('.*', TemplateView.as_view(template_name='index.html')) Is there perhaps something on Nginx that needs changing? I would guess not since I have other production sites working correctly (however none of them … -
Struggling with many to many field
I'm trying to create a new product. Here is my model : class Product(models.Model) : door = models.ForeignKey(Door, on_delete=models.CASCADE) options = models.ManyToManyField(Option) Here is my views : def new_product(request, door_id) : door = get_object_or_404(Door, id=door_id) checked = request.POST.getlist('checks[]') c_checked = [] for check in checked : new_check = get_object_or_404(Option, name=check) c_checked.append(new_check) product = Product.objects.create( door = door, options = c_checked, ) product.save() return render(request, "confirmation.html") Unfortunately, when I run the server, I get an error saying : Direct assignment to the forward side of a many-to-many set is prohibited. Use options.set() instead Please help me if you have the answer. . -
Django: adding registration form to homepage without turning it to a registrationview?
I'm using django-registration for my project. I am overriding the package's RegistrationView with my own RegistrationViewWithContext, which allows me to pass extra context to the form. urlpatterns = [ ... url(r'^accounts/', include('registration.backends.hmac.urls')), url(r'^accounts/register$', RegistrationViewWithContext.as_view(form_class=RegistrationFormUniqueEmail), name='registration_register'), ... ] This is working just fine at localhost:8000/accounts/register. But now what I want to do, is have the same form on the app's homepage/index: localhost:8000/. The view on this homepage is a function-view called dashboard, here's the relevant part: def dashboard(request): context = {} current_user = request.user if current_user.is_authenticated: # code to show dashboard for already logged-in user else: # code to show promo text and registration form context['form'] = RegistrationFormUniqueEmail() return render(request, 'dashboard.html', context=context) The form on the dashboard view is displaying just fine, but submitting it does nothing at all - it only redirects back to the homepage. I'm sure I need to add a an if POST clause here, but I'm not sure how should I build since the views, as said, are "hidden" for me, and are somewhere inside django-registration. I'm a little lost. Any ideas?