Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I count dynamically just use Django admin and write functions and views there?
I would like to develop a management system in Python with Django, Django admin site satisfies part of needs almost. Suppose there is 1 cabinet, and the cabinet has 6 layers, every layer can hold 80 books, so when I place a book on a layer, the number of cabinet, layer and panel need to be selected or input, the usage amount and surplus of cabinet need to be displayed dynamically. I really want to use admin page, just admin page, can I archive it? Really appreciate for any advice. class Cabinet(models.Model): number = models.CharField(max_length=128, verbose_name="Cabinet Number", null=True) history = HistoricalRecords() class Meta: verbose_name = 'Number of Cabinet' verbose_name_plural = verbose_name class Layer(models.Model): number = models.CharField(max_length=128, verbose_name="Layer Number", null=True) cabinet_no = models.ForeignKey( Cabinet, on_delete=models.CASCADE, verbose_name="Cabinet No.", related_name="+", null=True, blank=True) history = HistoricalRecords() class Meta: verbose_name = 'Number of Layer' verbose_name_plural = verbose_name class Panel(models.Model): number = models.CharField(max_length=128, verbose_name="Panel Number", null=True) history = HistoricalRecords() class Meta: verbose_name = 'Exact Position of Paper(Panel Number)' verbose_name_plural = verbose_name class Book(models.Model): cabinet_no = models.ForeignKey( Cabinet, on_delete=models.CASCADE, verbose_name="Cabinet No.", related_name="+", null=True, blank=True) layer_no = models.ForeignKey( Layer, on_delete=models.CASCADE, verbose_name="Layer No.", related_name="+", null=True, blank=True) position = models.ForeignKey( Panel, on_delete=models.CASCADE, verbose_name="Panel No.", related_name="+", null=True, blank=True) amount = models.CharField(max_length=128, … -
Is there any idea that i can put closing tag(/>) in text input tag of html in django form processing ?
//here is form in django code <form method="post" novalidate> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> //now the form is rendered as <input type="text" name="phone_email" required id="id_phone_email"> <input type="text" name="full_name" required id="id_full_name"> //now this html code doesn't have any input field closing tag(/>) any i am being able to run the jsx code because of the absence of closing input tag. -
How to update many to many Django REST?
How would I go about updating a many to many relationship in Django REST framework? Here is my model. class SchoolTeacher(AbstractBase): school = models.ForeignKey(School, on_delete=models.CASCADE, related_name='teachers') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='teacher_at',) subjects = models.ManyToManyField(SchoolSubject, related_name='teachers') Here is my serializer: class SchoolTeacherSerializer(serializers.ModelSerializer): .... def create(self, validated_data): school_class = validated_data.get('school_class', None) stream = validated_data.get('stream', None) school_teacher_model_fields = [ f.name for f in SchoolTeacher._meta.get_fields()] valid_teacher_data = { key: validated_data[key] for key in school_teacher_model_fields if key in validated_data.keys() } subjects = valid_teacher_data.pop('subjects') teacher = SchoolTeacher.objects.create(**valid_teacher_data) for subject in subjects: teacher.subjects.add(subject) self.add_class_teacher(stream, school_class, teacher) return teacher def update(self, instance, validated_data): subjects = validated_data.pop('subjects') school_class = validated_data.get('school_class', None) stream = validated_data.get('stream', None) teacher = instance for (key, value) in validated_data.items(): setattr(teacher, key, value) for subject in subjects: teacher.subjects.add(subject) teacher.save() return teacher How do I achieve updating subjects? Currently, I can only add and not delete existing subjects. -
Installing gettext in windows :Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed
I followed the instructor of installing gettext on windows and when I type xgettext --version in my command prompt it says that it has installed. but when I want to run this command: python manage.py makemessages -l "fa" in my project it says Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. I tried so hard but it seems there are no good answers out there -
Slim Jquery Plugin to ImageFiled n Django
i have a slim jquery plugin. What it does, it take a image and crop it, after croping it create input type field hidden and save value of base64 in it. so how can i upload that image to django -
How to handle two forms in a single template
I have two forms and I would like to display them both in the same template. wid in the objects table is a field that is referenced to the class w_orders and I would like that as soon a workorder is created an object should be created automatically also the wid to get automatically the Id of w_orders. This is my code: models.py class w_orders(models.Model): Id = models.BigAutoField(primary_key=True) datedefwo = models.DateField(default=datetime.now) datesched = models.DateField(blank=True, null=True) datefinished = models.DateField(blank=True, null=True) sign = models.BigIntegerField(blank=True, null=True) statusid = models.BigIntegerField(blank=True, null=True, default=1, choices=STATUS_CHOICES) typeid = models.BigIntegerField(blank=True, null=True, default=1, choices=TYPE_CHOICES) comments = models.CharField(max_length=254, blank=True, null=True) navid = models.BigIntegerField(blank=True, null=True) navkonsid = models.CharField(max_length=12, blank=True, null=True) navname = models.CharField(max_length=254, blank=True, null=True) navcustadr = models.CharField(max_length=254, blank=True, null=True) navdebt = models.FloatField(blank=True, null=True) navpropcode = models.CharField(max_length=254, blank=True, null=True) navdepcode = models.CharField(max_length=254, blank=True, null=True) navphoneno = models.CharField(max_length=254, blank=True, null=True) navreasoncomp = models.CharField(max_length=254, blank=True, null=True) nightshift = models.BooleanField(default=False) priority = models.BigIntegerField(blank=True, null=True) stid = models.BigIntegerField(blank=True, null=True) mapurl = models.CharField(max_length=254, blank=True, null=True) def __unicode__(self): return self.Id class objects(models.Model): oid = models.BigAutoField(primary_key=True) wid = models.ForeignKey(w_orders, on_delete=models.CASCADE) objtypegisid = models.BigIntegerField(blank=True, null=True, default=1) objgisid = models.BigIntegerField(blank=True, null=True, default=1) condgenid = models.BigIntegerField(blank=True, null=True, default=1) condriskid = models.BigIntegerField(blank=True, null=True, default=1) condratsid = models.BigIntegerField(blank=True, null=True, default=1) condmhcoverid = models.BigIntegerField(blank=True, … -
Nginx 403 for newly created files
My Django app is configured nginx. Media files are served by nginx directly. The issue I have now is that nginx is giving 403 forbidden for the pdf files i uploaded. Pdf files are uploaded to media/file directory. When i do sudo chown -R www-data:www-data media/file The file will be loaded. But when i upload another pdf, nginx is again returning 403. I have also tried sudo chmod g+s media/file That also did not work. So each time i have to run chown to make the file load. -
How do I connect to a PostgreSQL Database Server with Django?
I want to connect Django application with PostgreSQL Database Server on cPanel / Namecheap hosting. I have installed PostgreSQL in Django app using this command pip install psycopg2. And in settings.py i have used this code DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dev_devdap', 'USER': 'dev_devdur', 'PASSWORD': 'E0K09o1EC', 'HOST': 'localhost', 'PORT': '', } } -
Validate through parents model fileds
I have two models: class Foo(models.Model): from = models.ForeignKey(Place) to = models.ForeignKey(Place) class Bar(models.Model): foo = models.ForeignKey(Foo) place = models.ForeignKey(Place) I need to validate place field of Bar can be from or to. For example if I have from - London and to - New-York, I can choose place for child model only between this two places. How can I do in serializer? Thanks! -
django.db.utils.ProgrammingError: relation "auth_group" does not exist
I have a django project that has been under development but hadn't been tested yet. Recently I have been running the test command python manage.py test but I get the following error. psycopg2.ProgrammingError: relation "auth_group" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/core/management/commands/test.py", line 26, in run_from_argv super().run_from_argv(argv) File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/core/management/commands/test.py", line 56, in handle failures = test_runner.run_tests(test_labels) File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/test/runner.py", line 604, in run_tests old_config = self.setup_databases() File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/test/runner.py", line 551, in setup_databases self.parallel, **kwargs File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/test/utils.py", line 174, in setup_databases serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 68, in create_test_db run_syncdb=True, File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 148, in call_command return command.execute(*args, **defaults) File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 172, in handle self.sync_apps(connection, executor.loader.unmigrated_apps) File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 310, in sync_apps self.stdout.write(" Running deferred SQL...\n") File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 106, in __exit__ self.execute(sql) File "/home/teddy/Desktop/Mookh_Works/env/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 133, … -
Filtering using manytomany field based on logged user
Trying to filter a query based on a check if the user is added to the ManytoMany Field. Models.py class Book(models.Model): book_name = models.CharField(max_length=150) viewed_by = models.ManyToManyField(User) the view def get_new_books(request): print(request.user) new_books = models.Book.objects.filter(viewed_by__in=request.user) context = { 'new_books': new_books, } return context it returns the error 'User' object is not iterable -
When creating django model, it posts the data, but does not save it in database
I can create model objects through admin panel. But I want it to be created on website. The code below allows me to enter values of a model, and when I submit it, it redirects to the written url, which happens after form.save. This is the message from server "POST /taskcreate HTTP/1.1" 302 0. But there is no changes in database. What can solve this issue? Thanks models.py class Task(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=1000) pub_date = models.DateTimeField('date_published', auto_now_add = True) cost = models.IntegerField() def __str__(self): return '%s' % (self.name) forms.py class TaskCreateForm(forms.ModelForm): class Meta: model = Task fields = ('name', 'description', 'cost') views.py def TaskCreateView(request): if request.method == 'POST': form = TaskCreateForm(request.POST) if form.is_valid(): form.save return redirect('home') else: form = TaskCreateForm() return render(request, 'employer/create_task.html') -
Modifying jwt access token expiry time in django using simplejwt module
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView from rest_framework_simplejwt.utils import datetime_to_epoch SUPERUSER_LIFETIME = datetime.timedelta(minutes=1) class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super(MyTokenObtainPairSerializer, cls).get_token(user) token['name'] = user.username token['user_id'] = user.id if user.is_superuser: #token.set_exp(from_time=starttime,lifetime=SUPERUSER_LIFETIME) token.payload['exp'] = datetime_to_epoch(token.current_time + SUPERUSER_LIFETIME) return token class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer i have tried this code (followed this link: How can we assign different expiry time to different users in jwt tokens in django ). This code updates the expiry time of refresh token but i want to update expiry time of access token in django using simplejwt module. any suggestions please. -
Django contrib auth users manytomany
Hello i wabt to make several users to one post with manytomany relationship from django.contrib.auth.models import User class Post(models.Model): author = models.ManyToManyField(User) title = models.CharField(max_length=150) slug = models.SlugField(max_length=255, unique=True) body = models.TextField() but i got this error Post needs to have a value for field "id" before this many-to-many relationship can be used. Can anyone tell me wats the problem >? -
filter on related_set in Django query
class Hardware(models.Model): date = models.PositiveSmallIntegerField() node = models.ForeignKey('Node', on_delete=models.CASCADE,null = True) slot = models.PositiveSmallIntegerField(null = True) server = models.CharField(max_length=20,null = True) server_state = models.CharField(max_length=20,null = True) adapter = models.CharField(max_length=20,null = True) adapter_state = models.CharField(max_length=20,null = True) class Meta: unique_together = ('date', 'node','slot') order_with_respect_to = 'node' def __str__(self): return self.node.name +" " + self.server class Node(models.Model): name = models.CharField(max_length = 40, primary_key = True) def __str__(self): return self.name def inventory_by_node(request): day = (arrow.now().day) - 1 nodes = Node.objects.prefetch_related("hardware_set").all() return render(request, 'automation/inventory_by_node.html',{'nodes':nodes}) I need to filter hardware_set based on date which is equal to currrent day. I tried nodes = Node.objects.prefetch_related(Prefetch("hardwares", quesryset=Hardware.objects.filter(date=day)).all() but It didn't works says no Pretch is defined -
Any way to detect in Django whether a request URL end with a trailing question mark "?"
Basically asking this question, but for Python/Django: Java Web: Detect a URL with a trailing question mark and empty query string A trailing question mark can have poor influence on SEO (duplicate content). In our case, it's very hard to avoid this on the client side, so I'd like to make a redirect on the server side to the non-question-mark-trailing URL. However, I can't find a way to check in Django whether a null query string was sent. With and without "?" appended, request.GET is empty. Also, neither request.get_full_path() nor request.build_absolute_uri() do contain the "?" if no GET params are in request.GET. URL patterns don't capture query params at all. It would also be an option to capture and redirect this in NGINX, if anybody knows how ... Any ideas? -
Django, update my jinja variable in template
i have a problem, i trying to change my jinja variable when i call method post: Template <button id="button1">test</button> <div class="myclass"> {{ hosts.0.name }} <--- NEED TO CHANGE THIS VARIABLE </div <script> $('button1).click(function () { var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); $.ajax({ type:"POST", url: "myurl/", data: { gfilter: "yes", csrfmiddlewaretoken: csrftoken }, success: function(){ console.log("success"); } }); return false; }); View data = {} data['hosts'] = zapi.host_get() #get my initial dates try: if request.POST['gfilter'] == "yes": #<-- get dates after push button data['hosts'] = [{'name': 'test','host':'abc'}] except: print("except") print(data['hosts']) return render(request, 'zabbix/Templates.html', data) in view i want to recive my new data when i push the button, in view i see the data corectly but value of variable {{ hosts.0.name }} is not changed in template, Who know how resolve that case make me clear how thank you advance -
search results highlighting with custom template tag
my custom template tag to highlight query in search results. def highlight(text, word): return mark_safe(text.replace(word, "<Strong>%s</Strong>" % word)) it's working, issue is it is not ignoring case sensitive, I want to do it by using regular expression, have no idea weather mark_safe will support, didn't find any documentation are example in this scenario word =search query text =search result -
ModuleNotFoundError Django
After having setup a venv and starting a project getting the correct files (which i have double checked). i see that in the files the import statements are not working. views.py: from django.shortcuts import render from django.http import HttpResponse def home (request): return HttpResponse('<h1>header</h1>') # Create your views here. When running it returns this error: from django.shortcuts import render ModuleNotFoundError: No module named 'django' urls.py: from django.contrib import admin from django.urls import path from migrations import views urlpatterns = [ path('', views.home, name="header") ] Which returns this error: from django.contrib import admin ModuleNotFoundError: No module named 'django' Every project file's import statements for django have the red wavy underlining in pycharm meaning it cant find the module. How could I fix this and what could I have done wrong? Haven't found anything useful on the internet yet. -
How to maintain multiple records in auth_user table for the same local users in django-allauth
I'm trying to build the web login with different social accounts. And there is this situation where let's say a user login with Facebook and then log out and then later once again login with google then two different entries are created for the same local user. How to properly maintain these records. I'm not able to find proper documentation and video tutorials for these solutions. -
Running save() for all objects
I will be making a migration on my website today and I added new field(slug) and slugify method with save(). It goes like this: def save(self, *args, **kwargs): self.slug = slugify(self.tag+'-'+self.title) super(Image, self).save(*args, **kwargs) My model has about 50 entries and I don't want to be saving them all manually just to generate slug for all of them. Is there a way to do it automatically? -
Why do we need set enviroment variables in wsgi.py and manage.py not in settings.py?
I read tips for setting enviroment variables in python project and usually enviroment variables set in settings.py, but for Django project recommended to set environment valiables in wsgi.py and manage.py. What is advantages of this solution (instead of setting variables in settings.py)? from dotenv import load_dotenv # Load environment variables from .env file. load_dotenv(verbose=True) -
Migrate command create all tables on second DB - Django
I have an app (ali) on my project (website) and I wanted it to have its own database. The problem is, when I run python manage.py migrate --database=ali, the command recreates all tables within my ali database; whereas the expected result would be to have only the ali_search database. Settings: # website.settings ... INSTALLED_APPS = [ 'base.apps.BaseConfig', 'ali.apps.AliConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'django_comments', 'mptt', 'tagging', 'zinnia', ] .... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'website', 'USER': 'website', 'PASSWORD': 'website', 'HOST': 'localhost', 'PORT': '5432', }, 'ali': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'ali', 'USER': 'ali', 'PASSWORD': 'ali', 'HOST': 'localhost', 'PORT': '5432', } } DATABASE_ROUTERS = [ 'ali.routers.AliRouter', ] .... Router: # ali.routers class AliRouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'ali': return 'ali' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'ali': return 'ali' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'ali' or \ obj2._meta.app_label == 'ali': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'ali': return db == 'ali' return None Model: # ali.models from django.db import models class Search(models.Model): results = models.IntegerField() This is what I get by querying my ali DB with \dt: ali=# … -
Chat system using socket.io with django & nodejs
I am using django on 8000 & node on 4000 for a chat application using socket.now i am confused how to fix io initialization.& i want to apply socket on urls starting with /chat/. Any one can guide me ? -
Unable to migrate Django project, because of the 'auth' app
I updated Django from 1.11 to newest version. Also I updated Mezzanine. Now whenever I try to run the app, or migrate it, or showmigrations, or makemigrations, or fake mitrations, it crash with: Traceback (most recent call last): File "app/manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/commands/migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/loader.py", line 275, in build_graph raise exc File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/loader.py", line 245, in build_graph self.graph.validate_consistency() File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/graph.py", line 261, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/graph.py", line 261, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/graph.py", line 104, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0010_auto_20180912_1433 dependencies reference nonexistent parent node ('auth', '0009_alter_user_last_name_max_length') I do not really know what is the auth - it is not in my installed apps. This migration named: '0009_alter_user_last_name_max_length' is nowhere on my computer so I am out of ideas how to …