Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Partitions size for install Ubuntu or Mint on SSD+HDD
I will try to install Ubuntu or Mint on my notebook (i5, 8 Gb RAM). I have 120 Gb on SSD and 500 Gb on HDD. Please help me for partitions size on SSD and HDD. I will learn FullStack development via Python (Django and Flask). Thank for help! -
TypeError: initialize() got an unexpected keyword argument 'bytes_mode'
I have recently configured django on apache using modwsgi. It works fine when I disable authentication on my application. But, it gives below error when authentication is enabled. I am using django_auth_ldap module for authentication purpose. I am using Python 2.7, Django 1.11.15 and apache 2.4.6 version. Error logs:- [Wed Dec 19 14:23:30.351155 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] python version [Wed Dec 19 14:23:30.351187 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] 2.7.5 (default, Oct 30 2018, 23:45:53) [Wed Dec 19 14:23:30.351260 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] [Wed Dec 19 14:23:30.351290 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] django version [Wed Dec 19 14:23:30.351390 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] 1.11.15 [Wed Dec 19 14:23:30.359768 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] Internal Server Error: /login/ [Wed Dec 19 14:23:30.359839 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] Traceback (most recent call last): [Wed Dec 19 14:23:30.359855 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner [Wed Dec 19 14:23:30.359864 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] response = get_response(request) [Wed Dec 19 14:23:30.359874 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response [Wed Dec 19 14:23:30.359883 2018] [wsgi:error] [pid 17609] [client 100.81.144.164:55774] … -
Where to keep long hardcoded data for initial migration in Django?
I want to create two models something like this: class LogActions(models.Model): name = models.CharField(default='-') text = models.TextField() class Logs(models.Model): user = models.ForeignKey(User) log_message = models.ForeignKey(LogActions) date = models.DateField(auto_now_add=True) price = models.CharField(default='-', max_length=20) In LogActions there will be stored user actions. Example: Action one: name = 'USER_POINT_ADDED' text = 'User {user} added point to bla bla bla (long text...)' There will be like 20 actions, names of this actions will be short, but texts are very long. I don't know where to store all the initial data for migration... This data should be available through all project life. I want to create dict like: log_actions = { 'USER_POINT_ADDED': 'User {user} added... <verylongtexthere>', 'USER_POINT_EDITED': '<verylongtexthere>', 'USER_POINT_DELETED': '<verylongtexthere>', 'USER_GROUP_ADDED': '<verylongtexthere>', } All dicts like this above I hold in django settings.py file, but there are small and adding such a unclear hardcoded code to settings.py seems to be bad... but i need it for initial migration. I'm Junior Dev are there any good habits in Django to store big hardcoded data that is needed to initial migration on new pc/server? Did you met this kind of problem? How did you solve it? -
How To Capture All Templates And Static Files Before They're Sent To Client
In Django >= 1.11, how would I go about capturing the rendered HTML templates and statically served files to make programmatic changes to them before they are sent to the client? I had made a custom "render" function, but soon realized that this only works on rendered templates and not static files. I would like to capture all files served over the server, not just rendered ones. How would I go about doing this? -
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?