Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The database backend does not accept 0 as a value for AutoField
I have a Test model: class TestModel(models.Model): INACTIVE = 0 ACTIVE = 1 ARCHIVE = 2 STATUS = ( (INACTIVE, "Inactive"), (ACTIVE, "Active"), (ARCHIVE, "Archived"), ) field_01 = models.CharField(max_length=200) field_02 = models.ForeignKey(TestModel2, related_name='tests') field_03 = models.ForeignKey(TestModel2, related_name='tests_users') field_04 = models.IntegerField(default=1, blank=True, null=True) field_05 = models.IntegerField(default=1, blank=True, null=True) field_06 = models.DateTimeField(default='2000-10-10') field_07 = models.TextField(default='', blank=True, null=True) field_08 = models.TextField(blank=True, null=True, default='') field_09 = models.TextField(blank=True, null=True, default='') field_10 = models.ForeignKey(TestModel3, null=True, blank=True) field_11 = models.ForeignKey(TestModel4, null=True, blank=True) field_12 = models.ForeignKey(TestModel5, null=True, blank=True) field_13 = models.ForeignKey(User, related_name='user') field_14 = models.ForeignKey(User, related_name='creator') field_15 = models.IntegerField(default=INACTIVE, blank=True, null=True) field_16 = models.DateTimeField(default='2000-10-10') I try to change status to ARCHIVE by this code: test = TestModel.objects.get(id=self.kwargs['pk']) test.status = ARCHIVE test.save() and get this error: The database backend does not accept 0 as a value for AutoField. status field is not AutoField. Why this error happend? -
Wrong path in nginx to static page
Although I have the application in django, I want to set up a static page. Using nginx. But I get an error: [alert] 100983#0: *439266 "/path_to_page_on_server/press_page.htmlindex.html" is not a directory, Here is my url: url(r'^press/', TemplateView.as_view(template_name='press_page.html'), name='press') Here is my config in nginx include: location /press/ { alias /path_to_page_on_server/press_page.html; } I would like to under /press/ have page press_page.html. -
Create many requests to db
i wanna create Voucher system and want create request for admins, where they can add many voucher code with value. def randomString(stringLenght=8): letters = string.ascii_letters + string.digits return ''.join(random.sample(letters, stringLenght)) class VoucherCreateView(CreateView): model = Voucher form_class = VoucherCreateForm template_name = 'voucher/VoucherCreateView.html' success_url = reverse_lazy('voucher:voucher_create') def form_valid(self, form): x = self.request.POST.get('value_x') x = int(x) for i in range(0, x): i = randomString() e = Voucher(voucher=i, money=self.request.POST['value_money']) e.save() return super(VoucherCreateView, self).form_valid(form) Model looks like: class Voucher(models.Model): voucher = models.CharField(max_length=8, unique=True) money = models.SmallIntegerField(blank=True) created = models.DateTimeField(auto_now_add=True) used = models.BooleanField(default=False) and forms class VoucherCreateForm(forms.ModelForm): value_x = forms.IntegerField(required=True) value_money = forms.IntegerField(required=True) class Meta: model = Voucher fields = ['voucher', 'money'] and this want add to mysql requests or add but not the x like i want, any idea ? -
Django FileField not respecting null=False parameter
I have a Django FileField which is set to not nullable. However it is behaving like it is nullable. class Thing(BaseModel): document = models.FileField(null=False, blank=False) thing_id = models.CharField() # This does not raise but I would like it to Thing.objects.create(thing_id='123') -
Django 2.0 Upgrade - False Positives on urls.W001 Warning
I'm upgrading a Django project from Django 1.11 to Django 2.1.7, and after changing all the URL patterns to the Django 2 way of doing things, I'm getting a bunch of false positives on the urls.W001 warning when I do manage.py runserver. Example: ?: (urls.W001) Your URL pattern '^some-pattern/$' [name='some_name'] uses include with a route ending with a '$'. Remove the dollar from the route to avoid problems including URLs. When I look at that URL pattern in my urls.py file, however, it absolutely doesn't have a ^ or $ in it. path('some-pattern/', views.some_view_function, name='some_name'), I've blown away both my local virtualenv and my Vagrant box and started from scratch just to make sure it's not some lingering compiled stuff somewhere, but the behavior is the same when starting from scratch. Has anyone else run into this? The app itself seems to run fine, I'm just flummoxed at where Django might be seeing things that don't exist anywhere in my code. Thanks for any ideas anyone might have. -
How to properly configure nginx ssl for working with docker-compose and django-channel ssl socket
I have a django project with django-channels 2.X inside. Locally it works perfect, but with production I have problem of connecting this socket with front-end. 8:675 WebSocket connection to 'wss://air.my-server.com/excel-worker/' failed: Error in connection establishment: net::ERR_NOT_IMPLEMENTED My app has SSL certificate from LetsEncrypt. I've alreday tried all recommendation from here https://channels.readthedocs.io/en/latest/deploying.html and almost all, what i've found on Stackoverflow, Github (example: https://github.com/django/channels/issues/919). Also i've tried to configure nginx according to this https://www.nginx.com/blog/websocket-nginx/ but wothout luck. I'm sure problem is in my Nginx config. docker-compose.yml version: '3.0' services: project_db: image: postgres:9.6 container_name: air-db volumes: - ./src/data:/var/lib/postgresql/data - ./prj_config/docker-entrypoint-initdb.d/:/docker-entrypoint-initdb.d/ restart: unless-stopped env_file: - prod.env project_redis: image: redis:latest container_name: aircraft-redis restart: unless-stopped expose: - 6379 backend: &backend container_name: air-auto build: context: . dockerfile: Dockerfile command: sh -c "python manage.py makemigrations && python manage.py migrate && gunicorn service.wsgi -b 0.0.0.0:8112 --workers 1" restart: unless-stopped volumes: - ./src:/src depends_on: - project_db - project_redis ports: - 0.0.0.0:8112:8112 env_file: - prod.env channel-worker: <<: *backend container_name: air-channels command: sh -c "daphne -e ssl:443:privateKey=privkey.pem:certKey=fullchain.pem -u /tmp/daphne.sock -p 8005 service.asgi:application -b 0.0.0.0" depends_on: - project_db - project_redis volumes: - /etc/letsencrypt/:/etc/letsencrypt/ ports: - 0.0.0.0:8005:8005 - 0.0.0.0:8006:443 nginx (sites-enabled) server { listen 80; server_name my-server.com; include snippets/letsencrypt.conf; return 301 https://$host$request_uri; } server β¦ -
The use of two lists in one django tags 'for'. Django
I have two letters that I would like to show in my template at the same time. How can I do it in the template the fastest and easiest way? Where set_1 = A, B, C, D, ser_2 = result from my django queryset Is there something like the below? Any help will be appreciated {% for b in set_1 and a in set_2 %} <p>{{ b }} - {{ a }}</p> {% endfor %} -
Django deny large requests without nginx/apache
Here is a problem, there are constants in Django (in settings): FILE_UPLOAD_MAX_MEMORY_SIZE = N1 * (1024**2) DATA_UPLOAD_MAX_MEMORY_SIZE = N2 * (1024**2) Problem : it DOES NOT prevent of large request. It LOADS into temp directory anyway. After loading, it does not generating TooLargeError until i manually check payload manually. Is it basically possible to prevent loading large file or at least generate bad response using only Django resouces without any other instruments like nginx/apache? -
django has_perm always false
I have a issue using has_perm method of a user geted by id. should return true because i added using usr.user_permissions.add(p) i refresh the user object get again by id but still returned false. even when even in the admin it appears. if someone knows something else. Here I leave part of my setings, user model and example of the code I use class User(AbstractUser): name = models.CharField(max_length=50) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): ***********************settings*********************** AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'guardian.backends.ObjectPermissionBackend', ) 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.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters', 'administration', 'work', 'bank', 'providers', 'customers', 'users', ] **********************code example********************* url = reverse_lazy('user:list', kwargs={'id': self.kwargs['user']}) user_obj = User.objects.get(id =self.kwargs['user']) perm = Permission.objects.get(id =self.kwargs['perm']) if user_obj.has_perm(perm): print("removed") user_obj.user_permissions.remove(perm) else: print("add") user_obj.user_permissions.add(perm) success_message = "User perm changed" return HttpResponseRedirect(url) -
Django: How to determine if an object is referenced by any other object?
summary In Django, what is the simplest way to determine if there are any objects in our database that refer to a given object? details Consider this minimal example from Django's Related objects reference: from django.db import models class Reporter(models.Model): pass class Article(models.Model): reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) How can we determine if there are any objects, so not only Article objects, that point to a given Reporter object, either through a OneToOneField, a ForeignKey, or a ManyToManyField? In other words, we want to determine if there are any reverse relations to the given object. For Article it is easy, we can just get e.g. reporter.article_set.count(), but other models may be added later which also point to Reporter, and these will also have to be taken into account. -
Trying to use link tag in django
enter image description here The error is - Reverse for 'work' with arguments '('active',)' not found. 1 pattern(s) tried: ['mainpage/analysis/threadcount/(?P[0-9]+)/(?P[-a-zA-Z0-9_]+)$'] -
How to take name of user admin in html
I try to take the name of author for published article. in model class Artigo(models.Model): autor = models.ForeignKey('auth.User', on_delete = models.CASCADE) titulo = models.CharField(max_length = 100) categoria = models.CharField(max_length = 20) conteudo = models.TextField() data_publicacao = models.DateTimeField( default = timezone.now ) def publicacao(self): self.data_publicacao = timezone.now() self.save() def __str__(self): return self.titulo in view def noticias(request): artigos = Artigo.objects.filter(data_publicacao__lte = timezone.now()).order_by('data_publicacao') return render(request, 'noticia/noticias.html', {'artigos':artigos}) in html <h1>Noticias</h1> {% for artigo in artigos %} <div> <h1><a href ="">{{ artigo.titulo}} </a> </h1> <p>{{ artigo.conteudo }}</p> <p>Publicado em: {{ artigo.data_publicacao }}</p> <p>{{ artigo.autor.username }}</p>* </div> {% endfor %} this {{ artigo.autor.username }} dosen't work. I have error : Exception Value: invalid literal for int() with base 10: 'ElFrances' I don't know how to take the name of author or other detail -
Extending Django Oauth2 Application Model
I was trying to Extend Oauth2 Application Model using this link - https://django-oauth-toolkit.readthedocs.io/en/latest/advanced_topics.html#extending-the-application-model. But some problem comming while i am migrating - ValueError: The field oauth2_provider.AccessToken.application was declared with a lazy reference to 'oauth2.companyfieldaddedapplication', but app 'oauth2' isn't installed. The field oauth2_provider.Grant.application was declared with a lazy reference to 'oauth2.companyfieldaddedapplication', but app 'oauth2' isn't installed. The field oauth2_provider.RefreshToken.application was declared with a lazy reference to 'oauth2.companyfieldaddedapplication', but app 'oauth2' isn't installed. I have add oauth2 in installed_apps still it is giving error Settings.py installed_apps = [ 'apps.oauth2', ] OAUTH2_PROVIDER_APPLICATION_MODEL='oauth2.CompanyFieldAddedApplication' My Project Structure βββ apollo_project β βββ __init__.py β βββ settings.py β βββ settings.py.ren β βββ urls.py β βββ wsgi.py βββ apps β βββ oauth2 β β βββ admin.py β β βββ apps.py β β βββ __init__.py β β βββ migrations β β β βββ 0001_initial.py β β β βββ 0002_auto_20190215_1402.py β β β βββ __init__.py β β βββ models.py β β βββ tests.py β β βββ urls.py β β βββ views.py project_folder > apps > oauth2 > models.py from django.db import models from oauth2_provider.models import AbstractApplication from apps.company.models import Company class CompanyFieldAddedApplication(AbstractApplication): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='company') Traceback Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) β¦ -
InternalType of JSONField is shown as TextField
I am a beginner with DJANGO, I am working on a project where one of the models contains a JSONField. In the code at some point i need to detect and process the JSONField only and so I get the internaltype of the fields and if it turns out to be JSON field then I process it. for field in obj._meta.fields: #find the fields with JSONField type if obj._meta.get_field(field.name).get_internal_type() == 'JSONField': It works well on my machine, however when I upload the same code on the server, it does not execute, as, the internaltype of the JSONField is returned as a TextField and the logic fails there. What could be wrong and why is the JSONField being detected as a TextField? The postgres version being used on the server is 9.6.1 -
django importing AUTH_USER_MODEL
IΒ΄m trying to use settings.AUTH_USER_MODEL as a foreignkey in a model, but the "settings" part doesnΒ΄t seem to work. How should I import that? from django.contrib.auth.models import User class Tareas(models.Model): creador = models.ForeignKey(settings.AUTH_USER_MODEL, help_text="Estatus del contenido", blank=True, null=True, on_delete=models.CASCADE) Thanks! -
Get Complete history of Redmine Issue using Python API
How we can get the complete History of Redmine Issue using Python REST API. I used journals but not getting complete details like who has updated the issue and when it is updated and which things updated. Please help me. -
I can't access a Django template variable in JS script
I'm having trouble accessing the list param = ['foo','bar'] on myView.js. the JS code is treating param as if it were a string, but when I try JSON.parse(param) I get the error shown below. What am I missing here? myView.html: <script> window.obj = {}; obj.param = "{{ param | safe }}"; </script> views.py: def myView(req): context = {'param':['foo','bar']} return render(req, 'myView.html', context) myView.js: $(document).ready(function() { console.log(window.obj.param); //prints ['foo','bar'] console.log(window.obj.param[0]); //prints [ console.log(JSON.parse(window.obj.param)); // Uncaught SyntaxError: Unexpected token ' in JSON at position 1 //what I need to happen console.log(param[0]); // prints 'foo' }); -
sorl thumbnail media file not created
I'm trying to use sorl thumbnail with an image url from the model (from pyploadcare) which comes as a string {% thumbnail "featured.full_image_url" "x240" crop="center" as im %} <img src="{{ im.url }}" alt="{{ featured.name }}" class="img-responsive"> {% endthumbnail %} problem though is it returns a media path to a file and folder that doesn't exist <img src="/media/cache/5e/a5/5ea5bd795dd6c1cd2a375afb8ad55fec.jpg" alt="IM1848 = Classic Oak Natural" class="img-responsive"> this is how I define the media path in the settings file BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and an ls into this folder sammy@deco:~/webapp/decomagna/media/cache$ ls 1b the main folder 5e doesn't exist which makes me think it either isn't using the right folder or there's an issue with it. I've tried clearing the cache python manage.py thumbnail clear but it returns the same path I also did the migrate python manage.py migrate and I also setup memcached CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': 'unix:/tmp/memcached.sock', } } -
Django PasswordChangeDoneView logout after password change
I'm using Django's provided PasswordChangeView and PasswordChangeDoneView from django.contrib.auth. After successful password reset, I want the session to be invalidated and log the user out. The Django docs mention that update_session_auth_hash() make it so the user does not get logged out after changing passwords. How do I override this and make it so the user DOES get logged out after changing their password? -
unable to load the pickle file in views Django project
I am beginner to django, started a basic django project(generating endpoint for my python project). i put all my dependency files in one directory, i am able to import all files in views.py from dependency folder but i unable to import pickle file. i) i am unable to import pickle file, i even tried to converting it to dictionary and importing.. but it is also failed feature_dict = pickle.load(f) AttributeError: Can't get attribute 'Test' on i don't know what is this 'Test' and why i can't import!! ii) i copied that pickle file in the same directory where views.py exists. but couldn't get the data , it arrising file not found error.. i want to import pickle file in my django project views.py. can anyone please suggest a solution.. -
Deployment Forbidden You don't have permission to access / on this server
I am deploy my django app to Linode and i am using apache2 as server. When i first deploy my app it was doing fine running with the default django server, but when i configured apache2, i started getting the Forbidden You don't have permission to access / on this server. Apache/2.4.34 (Ubuntu) Server at 139.162.56.162 Port 80. I have research on stackoverflow and can't find any useful answer. Here is my code <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn β¦ -
Every time an user adds post his info gets repeated. How do I prevent that?
Every time an user adds a new post, country name in user's info get repeated. For example. Someone from USA adds post, I tried to use distinct 'country = Post.objects.all().distinct('country')' then I get this error 'DISTINCT ON fields is not supported by this database backend'. my views.py def countries(request): country = Post.objects.all().distinct('country') context = { 'posts': country } return render(request, 'users/countries.html', context) my models.py from PIL import Image from django.db import models from django.urls import reverse from django.utils import timezone from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser class User(AbstractUser): first_name = models.CharField(verbose_name="First name", max_length=255) last_name = models.CharField(verbose_name="First name", max_length=255) country = models.CharField(verbose_name="Country name", max_length=255) city = models.CharField(verbose_name="City name", max_length=255) email = models.EmailField(verbose_name="Email", max_length=255) def __str__(self): return self.username class Post(models.Model): title = models.CharField(max_length=255) country = models.CharField(max_length=255) city = models.CharField(max_length=255) address = models.CharField(max_length=255) email = models.EmailField(max_length=255) phone = models.CharField(max_length=255) website = models.URLField(max_length=255) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('users:blog') class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) my urls.py from django.urls import path from .views import UserRegistrationView, CabinetView, PostCreateView, PostUpdateView, PostDetailView, PostDeleteView from . import views β¦ -
Connection refused from staging server to Google, but only as www-data not as root
Attempting to validate an Android in-app purchase token from Django application running on Debian server (using Requests), but connection is refused. If I hit the same Google URL, using any of these methods, I get the expected 200 response: In browser from local machine; Using cURL as root on staging server; Using requests.get(url) in manage.py shell in the application's virtual environment as root. ufw status verbose Status: active Logging: on (low) Default: deny (incoming), allow (outgoing) New profiles: skip To Action From -- ------ ---- 5432 DENY IN Anywhere 22 ALLOW IN Anywhere 80 ALLOW IN Anywhere 443 ALLOW IN Anywhere 3306 DENY IN Anywhere 9200/tcp ALLOW IN Anywhere Anywhere ALLOW IN 192.168.0.1 5432 DENY IN Anywhere (v6) 22 ALLOW IN Anywhere (v6) 80 ALLOW IN Anywhere (v6) 443 ALLOW IN Anywhere (v6) 3306 DENY IN Anywhere (v6) 9200/tcp ALLOW IN Anywhere (v6) sudo iptables -L Chain INPUT (policy DROP) target prot opt source destination fail2ban-ssh-ddos tcp -- anywhere anywhere multiport dports ssh fail2ban-ssh tcp -- anywhere anywhere multiport dports ssh ufw-before-logging-input all -- anywhere anywhere ufw-before-input all -- anywhere anywhere ufw-after-input all -- anywhere anywhere ufw-after-logging-input all -- anywhere anywhere ufw-reject-input all -- anywhere anywhere ufw-track-input all -- anywhere β¦ -
How to fetch all records from 2 tables
I have 2 models class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) employee_id = models.CharField(max_length=13, unique=True) class UserRole(models.Model): employee_id = models.ForeignKey(CustomUser, to_field='employee_id', unique=True, on_delete=models.CASCADE) supervisor_id = models.CharField(max_length=20, null=True) and have defined seriallizers for both models class UserSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = models.CustomUser class UserRoleSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = models.UserRole consider i have 5 records in both tables How to fetch all records from both tables (email, employee_id, supervisor_id ) like, where CustomUser.employee_id = UserRole.employee_id I tried with models.CustomUser.objects.select_related('UserRole') But, not able to fetch records from UserRole table. Also, how to serialize the data of 2 serializers to create one object which holds all fields. Thanks in Advance -
Serialize foreign key object that is AbstractUser
I am serializing a model using the Django REST framework successfully, but would like to add a field from a related model. I have seen other posts describe how to do this using nested serializers, however mine is different because the other model I am trying to access is an AbstractUser class. I would like to serialize the UserDefinedEquipName field from CustomUser. models (some fields removed for clarity): accounts/models.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): UserDefinedEquipName = models.CharField(max_length=50, default = "Default equip",) .... builds/models.py from accounts.models import CustomUser from django.contrib.auth import get_user_model class Build(models.Model): author = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,) machineName = models.OneToOneField(max_length=50,blank=True,) .... So my thought is to pass the value into the serializer but can't seem to figure out how to access the value without getting error AttributeError: type object 'Build' has no attribute 'CustomUser' I have tried: My serializers.py: from rest_framework import serializers from .models import Data, Build, CustomUser from django.contrib.auth.models import AbstractUser class buildStatsAPI_serializer(serializers.ModelSerializer): equipName = Build.CustomUser.UserDefinedEquipName #also tried: #equipName = Build.CustomUser__set.all() class Meta: fields = ('id','author','machineName','equipName',) model = Build Am I missing something small here? Or is there a much better way of doing this. It seems like if this wasn't an AbstractUser class it would be much β¦