Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i get my application properties running on linux on a dashboard?
I am new to django and trying to create a django dashboard for our server monitoring purpose. Here i need to show following things 1. Who is logged in currently on centos running machine. 2. Who is accessing which file currently. 3. When any file is changed and who changed it. -
Annotate Min value of filtered related Model
I have a Track Model and these tracks have a weekly rank in different charts (charttype) class Track(models.Model): id = models.CharField('Unique ID', max_length=100, primary_key=True) title = models.CharField('Track title', max_length=100) ... class Rank(models.Model): id = models.AutoField(primary_key=True) trackid = models.ForeignKey(Track, related_name='rank') pos = models.PositiveIntegerField("Position", blank=True, null=True) charttype= models.CharField(max_length=10, choices=CHARTTYPE) ... I first query for a specific charttype: track_list_top100 = Track.objects.filter(rank__charttype='total') after that I want to annotate this QuerySet with the highest position for that track for that specific charttype: track_list_top100 = track_list_top100.annotate(highestpos=Min('rank__pos')) But what I get is the highestposition for all charts combined. In other words the filter that I've set in the first query filter(rank__charttype='total') is not used in the annotation. Any ideas how to do this? Thanks in advance. -
How to add a like button in django 2!!(i need help asap)
I am trying to add a like button on my website in django2,but wherever i read,the code seems to be very complex and is ususally done in django<2.0,can someone help me please? -
Django xhtml2pdf <pdf:toc /> Table of Contents Styling
I am working on Django to render a html page to PDF using xhtml2pdf module. From the documentation of xhtml2pdf, it mentioned that I can use <pdf:toc /> to automatically generate table of contents (TOC) with the heading in the html files and use the following styles to style the TOC: pdftoc { color: #666; } pdftoc.pdftoclevel0 { font-weight: bold; margin-top: 0.5em; } pdftoc.pdftoclevel1 { margin-left: 1em; } pdftoc.pdftoclevel2 { margin-left: 2em; font-style: italic; } It does work. However, I don't see the method of generating the TOC with leading dots. The output of my generated PDF look something like this: TOC with no leading dots - From pisa But the actual result that I am looking for is something like this: TOC with leading dots - From html2pdf Anyone know how to make the TOC leading dots? Thanks in advance. -
Django serves CSS files and Favicon but not images from root static when debug =false or in production
I have been working on a personal profile site and have an image for my cover page saved in my root static folder. I can see the cover image fine in the browser when debug is true but when debug is false or I am in production the file is a 404 error, no where to be found. The root directory also has a CSS file (style.css) and a favicon.ico which both show up fine when debug is set to false or I am in production, it is just the image that doesn't show/work. I also have a background image in the "Polls" app that shows up fine in both debug=false and production. Here is an image of my file directory: Directory Here is my settings.py which, based on Django documentation and Heroku deployment documentation, should be configured correctly: import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'NUNYABIZNESS' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # DEBUG = bool(os.environ.get('DJANGO_DEBUG', True)) … -
Serialize extra object with request data and save to db django
def post(self, request, pk): studio = Studio.objects.get_studio_by_id(pk) data = request.data I want to serialize data and studio and save it serializer = BillingInfoSerializer(data=data) if serializer.is_valid(): serializer.save() -
Problems with Django model relations
I've little problem with django models. I'm trying to create a game statistics service, but can't figure out how could I pick players from each team as a starting roster (doesn't contain all of the team players) of the game. Picking should work so that home and visitor has separated player lists. And then it should be possible to create eg Goal object where I could pick player as scorer only from the starting roster. I've already tried to put home and visitor players as ManyToManyField in the Game model, but it won't work. It needs some filtering at least. class Game(models.Model): series = models.ForeignKey(Series, related_name="game_series") date = models.DateTimeField(default=None, blank=True, null=True) home = models.ForeignKey(Team, related_name="game_home") visitor = models.ForeignKey(Team, related_name="game_visitor") class Goal(models.Model): game = models.ForeignKey(Game, related_name="goal_game") minutes = models.PositiveIntegerField(default=None, blank=True, null=True) seconds = models.PositiveIntegerField(default=None, blank=True, null=True) scorer = models.ForeignKey(Player, related_name="goal_scorer") assist = models.ForeignKey(Player, related_name="goal_assist") class Save(models.Model): game = models.ForeignKey(Game, related_name="save_game") player = models.ForeignKey(Player, related_name="save_player") count = models.PositiveIntegerField(default=None, blank=True, null=True) The question is: how should I modify models to achieve the desired result? Note: I'm using admin views for data input, so the proposed resolution should work from there. -
WebpackError Module not found: Error: Can't resolve './__generated__/AdviceEntry_entry.graphql'
In my python django with react I am facing issue attached below, I am new at this level please advice. -
Django; How to take argument from template? [duplicate]
This question already has an answer here: How do I create a Django template tag with two arguments? 1 answer I've been working on Django project. I want to use templatetags for each object in queryset. So I'm wondering if there's a way to pass argument from template to templatetag. What I want to do is like this in views.py, it passes a queryset into template as a context. and in template, I will do for loop. {% load app_name_tags %} {% for entry in entries %} <!-- I want to use templatetag here for each object --> So I want to take each object as an argument. Anyone who can give me tips? -
How can I directly access an instance of a django message via django template?
As a part of my error response I am trying to add "show" to a collapsable container using something like: class="{{request.session.registration}}" but instead of session use django messages so the "show" does not persist. Right now I'm using a pretty janky workaround where I loop through all messages: <form action = "registration" method = "POST" id="registration" class="collapse container {% for message in messages %} {% if 'registration' in message.tags%} {{message}} {% endif %} {% endfor %} "> for reference, the message is added in the views.py via: messages.info(request, 'show', extra_tags='registration') How can I call this message explicitly? -
Django-Tteebeard using treadbeard field forms in django forms
I am trying to use TreeBeard's built in Form's with django forms (not admin). I specifically wanted to replace the rendering of a Select ForeignKey field with TreeBeard forms format. I thought I could do this by declaring the field in my ModelForm, but I've had no success. I'm new to django so my understanding is limited. These are my initial classes in my forms.py MyCategories = movenodeform_factory(Category) class CreatePost(ModelForm): class Meta: model = Post fields = ['title', 'category', 'region', 'content', ] I tried implementing it by declaring the category field in the beginning but this clearly isn't the way to do it. The declaration does return an html formatted category list, but I can't replace the Post category (which is a ForeignKey)with it. class CreatePost(ModelForm): category = movenodeform_factory(Category) class Meta: model = Post fields = ['title', 'category', 'region', 'content', ] The reason I want to use TreeBeard forms is because of the way it nests the fields according to the category hierarchy. -
How to disable Django signals in View?
Sorry for noob question, I'm writing a migration script and i don't want the signals to be triggered. How do i disconnect signal from views? View.py pre_save.disconnect( pre_save_callback, sender=MyModel) Error: NameError: name 'pre_save_callback' is not defined Thanks in advance! -
How can I get Django REST Authentication to work?
I'm having trouble understanding how to get authentication to work. I have set up a basic api, and I am trying to get any type of authentication to work (Basic Authentication to start with). But no matter what I do, I am able to retrieve information from the database (using Postman) without entering a username or password. What am I doing wrong? Here is my class: class User(models.Model): birthdate = models.DateField() gender = models.CharField( max_length=1, choices=(('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ('U', 'Unspecified')) ) join_date = models.DateField(auto_now_add=True) username = models.CharField(max_length=25, unique=True) password = models.CharField(max_length=25,) Here is my view: def user_tester(request): permission_classes = (IsAuthenticated,) if request.method == 'GET': objs = User.objects.all() serializer = UserSerializer(objs, many=True) return JsonResponse(serializer.data, safe=False) Here are the relevant settings: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } 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.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', Please advise on what I am doing wrong. I have some experience with Django, but none at all with authentication or permissions. -
How can I move my existing Django project on a cookiecutter-django project?
When I started learning Django, I created my Django project with the command django-admin startproject mysite. After that, I found out cookiecutter-django, and I wanna move my Django project onto the coockiecutter-django, upgrading to Django2. The first issue I faced to is django.db.migrations.exceptions.InconsistentMigrationHistory: Migration account.0001_initial is applied before its dependency users.0001_initial on database 'default'. In my Django project, I already have accounts app which does the same thing with users in cookiecutter-django. I researched about the issue, and found that I need to start over my Django project, but since it is already running on production server. I can't reset it. If I reset, it wouldn't be goona work when it's on production server. Is it really true that there is no way to solve the issue? -
Cannot push Django Python project in Heroku
I try to push the Python project (Python 3.7.0) to Heroku. It's a django project with mysql database linked. But it keeps show that the error: ModuleNotFoundError: No module named 'ConfigParser'. Is really the version 3.7.0 not compatible to Heroku? I try to pip install ConfigParser in the command, but it still not work. Does anyone meet this problem? Here's the error when pushing project in Heroku: remote: Complete output from command python setup.py egg_info: remote: Traceback (most recent call last): remote: File "<string>", line 1, in <module> remote: File "/tmp/pip-build-1fjjz1dy/MySQL-python/setup.py", line 13, in <module> remote: from setup_posix import get_config remote: File "/tmp/pip-build-1fjjz1dy/MySQL-python/setup_posix.py", line 2, in <module> remote: from ConfigParser import SafeConfigParser remote: ModuleNotFoundError: No module named 'ConfigParser' remote: remote: ---------------------------------------- remote: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-1fjjz1dy/MySQL-python/ remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to fathomless-citadel-89649. -
Is it OK to delete default database migrations for app using a non-default database connection?
I use multiple DATABASE keys (connection names) in my settings.py, for various apps, some using mysql, some using postgresql. I noticed that in the default database table django_migrations it also stores migrations for those apps that are NOT using the default database. Is it OK if I delete them? Or if they are needed, what are they used for? -
Can I create admin for each groups in django admin?
Let's say I have two groups named Group1 and Group2 having specific access to models. And I want to create an admin for each group so that, admin can do all CRUD done by the user of that group. Group1 admin should handle Group1 users activities and Group2 admin handle Group2 user activities. And also the user in each group can update, delete and view of its own. I want in Django admin. How can I do that? -
django models-design: "ptr field is required"
I'm using Python 3.6+PostgreSQL 10+latest Django and DjangoRestFRamework. I have the following models, in which several models inherit from a class which is the ForeignKey (One-to-Many) of another class. class Voteable(models.Model): Voteable_id = models.BigAutoField(primary_key=True); class base(Voteable): class Meta: abstract = False class traslated_info(models.Model): info_about=models.ForeignKey(base) info_body=models.TextField() info_language=models.CharField(max_length=2) class A(base): A_id=models.BigAutoField(primary_key=True) A_field=models.TextField() class B(base): B_id=models.BigAutoField(primary_key=True) B_field=models.TextField() B_belongs_to=models.ForeignKey(A) class C(base): C_id=models.BigAutoField(primary_key=True) C_field=models.TextField() C_belongs_to=models.ForeignKey(A) C_belongs_to=models.ForeignKey(B) Whenever I try saving an object A (via curl), django says that base_ptr is required. I don't know how to model this situation. The end user is not expected to create item base and then item A, B or C. I tried class base as abstract, but an abstract class can't be ForeignKey. I want to automatically create a base class whenever a class A is created. I think I have two options: A) Remove the ForeignKey and store the language-specific info fields as HStoreField. This makes the code somewhate dependent on Postgree. B) Create some sort of routine that automatically creates parent base item whenever a child A item is created (preserving the one to one relationship). What do you recommend? Is there some django easy option I'm missing to make option B? I have not found this. … -
Relation does not exist django migrations
I'm deploying a django application on an EC2 instance and have the following models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) foto = models.CharField(max_length=200, default="static/batman-for- def __str__(self): return str(self.user.first_name) + " Profile" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() When I login using the django user, I get the following error: ProgrammingError at /admin/login/ relation "profiles_profile" does not exist LINE 1: ..."."profiles_profile" FROM "profiles_... coming from: /home/ubuntu/chimpy/profiles/models.py in save_user_profile instance.profile.save() I've looked into the postgres database and I can't find a table called Profile so I guess my migrations failed, when I run python manage.py showmigrations it shows: admin [X] 0001_initial [X] 0002_logentry_remove_auto_add auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial but nothing about the other tables (including the profile one). I also want to mention that when I create a super user in the terminal I get the following error: django.db.utils.ProgrammingError: relation "profiles_profile" does not exist LINE 1: INSERT INTO "profiles_profile" ("user_id", "foto", "exchange... what am I doing wrong? Thanks -
How to make the initial migration for a DB that diverged from the corresponding models?
Situation: a project I'm working in had a file corruption or something. Models are the latest version, but the SQLite DB had to be rolled back before some columns were added/removed/modified. Migration files are all gone. Trying to create migrations anew results in the new columns being present in the initial migration file, so I can neither migrate for real (due to the table existing) nor fake it (since the columns are missing in the DB). Given those circumstances, how can I make an initial migration matching the columns currently present in the DB so I can fake it and then make a real second migration to bring the tables in line with the models? The only thing that comes to mind is manually tweaking the models to match the DB schema, making the initial migration, faking it and then restoring the new version of the models, but I'd much prefer having this done automatically. -
Using Facebook Bot to message and read Inbox Group Chat messages - django
I'm using Python / Django, and I need help building a Facebook bot to post and read messages from a personal group chat. I finished app approval for pages_messaging permissions, setup webhooks, Ngrok and all, but it seems I've been working on a Bot API that interacts with users from a Facebook page. I've been unable to find specifically what I need. I see references for read_messages permissions, and me/messages edge/field but those have been deprecated. What's the best route to go about accomplishing my goal? I've been unable to find what I'm looking for in the Facebook Graph API Docs. Even steps in the right direction would be great. Thanks! -
Cannot delete an sql object in Django
I'm working on a Django project and I have a problem with deleting an object. I have a model called Order and it looked like this: class Order(models.Model): name = models.CharField(max_length=64) price = models.IntegerField() add = models.CharField(max_length=128) size = models.CharField(max_length=5, default="Undefined") guest = models.CharField(max_length=64, default="Anonymous") I've already had an object and I decided to add another integer row. I forgot that integer rows must have integer default values and I just typed 'undefined'. When I made migrations, that was applied to my existing object but also gave me the following error: ValueError: invalid literal for int() with base 10: 'undefined' I've removed default value in the row but everytime I want to migrate (makemigrations works fine) I get the same error (this error above). All I have to do is to delete this 'broken' object but I can't. I tried: Orders.objects.all().delete() it gave me the same error. And I also cannot access to this table via Django admin because of this error. What should I do? -
Django open iOS/android App if installed
I am trying to find out how to open my iOS App after e.g. registration process on my website. In case that the user works on his desktop client or does not have the App on his mobile device, I want to redirect him to the standard website URL. If the user has the app installed i would like to open the app with (iOS Scheme) myapp:// . Thanks! -
Django: The HTML template fails to be converted to PDF
I am fairly new to Django and also JS/Jquery. I am trying to generate a pdf view of my HTML template, upon clicking the "Approve" Button. I have also written a js/jquery script within the same template to generatea pdf and instead I'm redirected to my homepage; just as I have defined it to do so in the corresponding view method. I'm wondering now why it does not run the js/jquery script and keeps referring to my view method and also what can I do to make it go through the script and convert the page to PDF and downloads it for the user, after hitting "Approve" Button. Many thanks for your smart comments ! My Template <!DOCTYPE html> {% load staticfiles %} <html> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="{% static 'css/quote_letter_est.css' %}"> <script src="https://code.jquery.com/jquery-1.12.3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/0.9.0rc1/jspdf.min.js"> </script> <title>Estimate Quote Letter</title> <script> var doc = new jsPDF(); var specialElementHandlers = { '#editor': function (element, renderer) { return true; } }; $('#Approve').click(function () { doc.fromHTML($('#content').html(), 15, 15, { 'width': 170, 'elementHandlers': specialElementHandlers }); doc.save('sample-file.pdf'); }); </script> </head> <div id="content"> <body bgcolor="#ffffff" border="1"> <form action="http://{{host}}:{{port}}/label/approve001" method="Get"> {%csrf_token%} {% block content %} {% if cust_data %} {% for row in cust_data %} … -
Error in migrate, but table is created. How can I fix it?
I have a problem in the process of migrating my table in Django. I'm using the Django 1.9 project and changing the design pattern, but when I made the change, there was a change in the table but the error popped up. How can I solve this? My migration: operations = [ migrations.CreateModel( name='Phases', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateTimeField()), ('assign', models.DateTimeField(null=True)), ('conp__id', models.IntegerField(null=True)), ('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='pow.Customer')), ('ops', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='pow.Process')), # ('phase', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='pow.Fase')), ('card', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='pow.SC')), ], options={ 'db_table': 'phase', }, ), ] Erro: raise ValueError(self._pending_models_error(pending_models)) ValueError: Unhandled pending operations for models: pow.fase (referred to by fields: pow.Phases.phase)