Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot access to the second user
I am learning Django 2.2 using chart js, I trying to display my user skill when changing the id in the URL. I have 2 users, it is working for the first but not the second. Here is the error: Profile matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8080/skills/2/ Django Version: 2.2 Exception Type: DoesNotExist Exception Value: Profile matching query does not exist. Here is my profile model, Profile => models.py : from django.db import models from django.contrib.auth.models import User from django.core.validators import FileExtensionValidator # Create your models here. class Profile(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) website = models.URLField(blank=True) avatar = models.ImageField(upload_to='uploads/img', validators=[FileExtensionValidator(allowed_extensions=['png'])], blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) @property def get_created(self): return self.created.strftime("%m/%d/%Y, %H:%M:%S") def __str__(self): return "{}-{}".format(self.name, self.get_created) Here is my Skills models, Skills => models.py from django.db import models from profiles.models import Profile from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class Skill(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) name = models.CharField(max_length=220) score = models.PositiveIntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)]) def __str__(self): return "{}-{}-{}".format(self.user, self.name, self.score) Here is my Skills url, Skills => urls.py: from django.urls import path from .views import skill_view, UserChartView app_name = 'skills' urlpatterns = [ path('', skill_view, name='my-skills'), path('<profile_id>/', UserChartView.as_view(), name='user-skills'), ] Here … -
How to setup a model as default value of a OneToOne field in Django
I added a new model to my existing design to handle the new requirements. To do the migrations, existing data requires default values to keep up with new model designs. How to assign an empty object as default value. class NewModel(models.Model): somedata = models.IntegerField(default=0) class TheExistingModel(models.Model): data1 = models.IntegerField(default=0) newfield = models.OneToOneField(NewModel, on_delete=models.CASCADE, default= "?" ) The new field is added to the existing model and it requires a default value so that existing data in the database are updated. Also when new TheExistingModel instance is created the respective NewModel has to created. -
Django - which create() method to override before saving incoming data as object
I have the following model in my models.py file: class Video(models.Model): created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=100, blank=True) video = models.FileField(upload_to='Videos/', blank=True) gif = models.FileField(upload_to='Images/', blank=True) class Meta: ordering = ('created', ) Before Django creates an instance of this model, I want to set the gif field on the Django site. So, the data comes to Django from the client site with the field video set, and based on the video field's content I want to fill the gif field. For that, which create() method do I need to override for this task? The create() method of my VideoSerializer class in serializers.py : def create(self, validated_data): return Video(**validated_data) Or the create() method of my VideoCreate class in views.py: class VideoCreate(generics.CreateAPIView): queryset = Video.objects.all() serializer_class = VideoSerializer parser_classes = (MultiPartParser, ) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) Hope someone can help -
How can i call kotlin file function or function which is in .kt file from java script?
How can i call kotlin file function or function which is in .kt file from JavaScript file? In other words how can i import kotlin class in javaScript/.js file? -
How to fix this error django.db.utils.OperationalError: could not translate host name "db" to address . Docker
I am using Pyscopg. DOCKER-COMPOSE: version: '3.7' services: web: build: . command: python3 /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db2 db2: image: postgres:11 SETTINGS.PY: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db2', 'PORT': 5432 } } Getting this Error: django.db.utils.OperationalError: could not translate host name "db2" to address: Temporary failure in name resolution -
how to create charts based on fields in django
Hi I'm trying to create charts showing data counts for the country, gender, and organization fields which would change as I filter the data, can anyone help me with this, I'm still new with web development, and this is my first project. I want to show this in the index.html file index.html <!DOCTYPE html> <html lang="en"> {% load widget_tweaks %} <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>Dashboard - SB Admin</title> <link href="static/css/styles.css" rel="stylesheet" /> <link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet" crossorigin="anonymous" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/js/all.min.js" crossorigin="anonymous"></script> </head> <body class="sb-nav-fixed"> <nav class="sb-topnav navbar navbar-expand navbar-dark bg-dark"> <a class="navbar-brand" href="index.html">Start Bootstrap</a><button class="btn btn-link btn-sm order-1 order-lg-0" id="sidebarToggle" href="#"><i class="fas fa-bars"></i></button ><!-- Navbar Search--> <!-- Navbar--> <ul class="navbar-nav ml-auto ml-md-0"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" id="userDropdown" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="fas fa-user fa-fw"></i></a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userDropdown"> <a class="dropdown-item" href="#">Settings</a><a class="dropdown-item" href="#">Activity Log</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="login.html">Logout</a> </div> </li> </ul> </nav> <div id="layoutSidenav"> <div id="layoutSidenav_nav"> <nav class="sb-sidenav accordion sb-sidenav-dark" id="sidenavAccordion"> <div class="sb-sidenav-menu"> <div class="nav"> <div class="sb-sidenav-menu-heading">Core</div> <a class="nav-link" href="index.html" ><div class="sb-nav-link-icon"><i class="fas fa-tachometer-alt"></i></div> Dashboard</a > <div class="sb-sidenav-menu-heading">Interface</div> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseLayouts" aria-expanded="false" aria-controls="collapseLayouts" ><div class="sb-nav-link-icon"><i class="fas … -
what should i do to remove the error of importing nltk as i have already installed it?
I have installed nltk and now it's not working, and I need assistance figuring out what's wrong. Installed via pip it is showing the error that " Please use the NLTK Downloader to obtain the resource" how to solve this? -
How to use django-hosts with Nginx
I have created one Django app which has two apps named "api" and "consumer". Now I want to use subdomains for both of this app. Like api.server.com and server.com. I searched online and found django-hosts so I implemented in my localhost and its working fine. After that I deployed it on AWS EC2 instance and created subdomain in Godaddy and point both root domain and subdomain to my instance IP. Root domain is working fine but when I try to go api.server.com, it shows me default Welcome to Nginx screen. Please help me with this issue. nginx.conf server{ server_name server.com, api.server.com; access_log /var/log/nginx/example.log; location /static/ { alias /home/path/to/static/; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } -
Django save default value in Proxy Model
Different proxy models should be different in type. If I query those models I the right ones. I am trying to save a default type field in a proxy model. I don't want to set it everytime in the view. This does not work. The type field is always "TYPE1". models.py: class MyModel(models.Model): class ModelType(models.TextChoices): TYPE1 = 'TYPE1', _('TYPE1') TYPE2 = 'TYPE2', _('TYPE2') type = models.CharField(max_length=100, choices=ModelType.choices, default='TYPE1') class Type2Manager(models.Manager): def get_queryset(self): return super(Type2Manager, self).get_queryset().filter(type='TYPE2') def save(self, *args, **kwargs): kwargs.update({'type': 'TYPE2'}) return super(Type2Manager, self).save(*args, **kwargs) class Type2ProxyModel(MyModel): class Meta: proxy = True objects = Type2Manager() views.py: def create_type2_model(request): form = Type2Form(request.POST, initial={}) f = form.save(commit=False) f.save() forms.py: class Type2Form(ModelForm): class Meta: model = Type2ProxyModel -
Nginx rewrite after proxy pass
I am using Django + Gunicorn to serve files and nginx as a static file server, you can see a part of the configuration file below location /static/ { root /some/folder; } location / { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; } What I want to do is to access static files without putting /static/ into url. As I see it, if there is initially no /static/ in the url, than the request should be passed down to Django (/). If there is /static/, than then it should be cut away and the appropriate static file should be served. I heard this can be achieved with rewrite directive, however, I don't understand, how to make such a check for /static/ presence -
Django: How to correctyl use signals to send automatic email to user when new account is created?
I develop a Django porject and I use Django Authentification I have added an Profile models that is linked to User and Site models I want to use signal to send automatic email with username and password (plaintext) to user when user account is created I face many to problems: as User is linked to Site model by FK, site attribute in Profile can't be NULL; I resolved it for the moment adding a default value but it is not satisfactory User instance is created in two steps: first username and password are registered and if username and password are valid, user instance is created and in a second admin form we can set other attribute and particularly email -> currently, signal post_save is send after username and password are registered; I would like email to be send when USer instance is complete registered because I need email to be available... When created, password is encoded by pbkdf2/sha256 so kwargs['instance'].password return encoded password; How can I send user plaintext password? models.py class Profile(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE pro_ide = models.AutoField(primary_key = True) user = models.OneToOneField(User, on_delete = models.CASCADE) site = models.ForeignKey(Site,default=1, on_delete = models.CASCADE) ... class Meta: db_table = 'adm_pro' verbose_name_plural … -
Why annotate dupliquates my queryset objects?
Whenever I use Annotate with Case/When logic to return a boolean, the resulting queryset is twice as long. Model : class Message(models.Model): readers = models.ManyToManyField(Compte, related_name='messages') Message.objects.count() // return 800 Then : qs = Message.objects.annotate(read=Case( When(readers=Compte.objects.first(), then=Value(True), default=Value(False), outputfield=BooleanField())) qs.count() // return 1600 What am I missing here ? Django 2.2.9 / PostgreSQL -
Django forms can I change the default "Username" field in Django forms to "Job Title"
I'm trying to make a form for a service providers booking app as part of a project. I'm just wondering can I change the default "Username" field in Django forms to "Job Title". Here is my current "Forms.py file. from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'password1', 'password2' ) def save(self, commit=True): user = super(UserRegisterForm, self).save(commit=False) user.first_name = cleaned_data['first_name'] user.last_name = cleaned_data['last_name'] user.email = cleaned_data['email'] if commit: user.save() return user -
Django custom middleware request.user always AnonymousUser
I'm using Django 2.2 and DRF In my application, based on the user property, I need to change the request.user to a different user. class CustomMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): print(request.user) response = self.get_response(request) return response The print(request.user) always gives AnonymousUser object but it gives the authenticated user in the views. How can I get the user in the middleware? -
dajngo admin date input format issue
I use django2.0 and postgresql9.6, and I have model.py: class model_test(models.Model): start_date = models.DateField('start') stop_date = models.DateField('stop') and I register it in admin.py: admin.site.register(model_test) So I can insert it on admin-site, but my pg database's has start_date like '20200101', and my insert date is default '2020-01-01', I want to change my insert to '20200101', I tried setting.py: USE_L10N = False DATE_FORMAT = 'Y%m%d' it does not work for me. How to do this? And my second question is I don't want to show the textbox, just show the date-piker: How to solve this? Thanks! -
Django template: Display object in template not using view
This almost feels too simple but I'm trying to show an object in my template and I can't use a function/class-based view because this needs to be on the base.html template (for all views). I totally get the problem as I can make it work when I define the object as a variable in a view. My question is really about how to make it work when not using the view.py base.html <!-- works --> {{ user.username }} <!-- doesn't work --> {{ custom_model.field }} I checked out The Django template language and using their story model as an example. -
How can I deploy Django App to 1and1 (ionos)
I created a website with Django and now I need to deploy it and now I have to upload it to 1and1. Do I need a specific tool for this or can I upload it without hesitation like a website that only contains .html and .css files? -
Django admin handling multiple forms
I created a custom model form class ProductGroupCommonForm(forms.ModelForm): items = forms.CharField(widget=ProductPairInputs) place = forms.MultipleChoiceField(choices=[(obj.place, obj.place) for obj in IapPlace.objects.all()]) class Meta: model = Product fields = ( 'name', 'product_order', 'place', 'tag', 'items', 'managed_by_promotion', 'asset', 'user_segment') def __init__(self, *args, **kwargs): super(ProductGroupCommonForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-2' self.helper.field_class = 'col-md-4' I am sending my custom form to overrided admin/change_form.html, like that def changeform_view(self, request, object_id=None, form_url='', extra_context=None): extra_context = extra_context or {} extra_context['product_common_form'] = product_common_form return super(ProductGroupModelAdmin, self).changeform_view(request, object_id, form_url, extra_context=extra_context) And i added this html custom change_form html is like {% load crispy_forms_tags %} <div class="form-group product-common"> {% crispy product_common_form %} </div> Now i want to get back that form data from my ModelAdmin class, How can i acces this post data ? -
AttributeError (Django)
I am getting an error 'FeedBackForm' object has no attribute 'FeedBackForm'.I have tried all troubleshooting steps but no luck..It'll be much appreciable if anyone can help. a)form.py file from django import forms class FeedBackForm(forms.Form): name=forms.CharField() Ldap_id=forms.CharField() email=forms.EmailField() company_name=forms.CharField() feedback=forms.CharField(widget=forms.Textarea) b)views.py from django.shortcuts import render from testapp import forms # Create your views here. def feedback_view(request): form = forms.FeedBackForm() # As here we are sending details to register.html and in html file we have not mentioned action wher this file will go # so it will come back here in views.py file only. :) if request.method == 'POST': form1 = form.FeedBackForm(request.POST) if form1.is_valid(): print("Form Validation sucess and printing feedback info") # Now to capture data we will use cleaned_data===>cleaned_data==>{name:value} print('Name of editor:', form1.cleaned_data['name']) print('LDAP of editor:', form1.cleaned_data['Ldap_id']) print('EmailId:', form1.cleaned_data['email']) print('Company:', form1.cleaned_data['company']) print('Feedback provided:', form1.cleaned_data['feedback']) ##Note this above if form.is_valid(): will start working only when we'll submit form otherwise it will not start. my_dict = {'form': form} return render(request, 'testapp/register.html', context=my_dict) c)urls.py file from django.contrib import admin from django.urls import path from testapp import views urlpatterns = [ path('admin/', admin.site.urls), path('register/',views.feedback_view), ] -
Format for Storing Interactive Documents in Database
Which format can I use to store interactive elements inside of a document oriented database, which allows us to easily derive a form out of it? Background: We have the use case of storing a document in a database, with basic structures within like: heading, itemizations, enumerations, paragraphs, etc. but also with interactive elements like a checkbox, etc. From this document we want to create an interactive (HTML) document, where users can check checkboxes, and submit the result back to the server. Normally we would model the (static) document with its components as tables and columns, and e.g. a checkbox as bool field, paragraphs as varchars etc. However, we want to dynamically create and store such documents, and therefore want to use a document oriented database, e.g. MongoDB. But we are unsure about which format we should use for that. Are there any JSON or alike formats we could use and derive a form out of it? Currently we see JSON forms and JSON schema as a possibility, but then we see that we must model all elements we need, for the structural elements of such a document, e.g. paragraphs, itemizations, headings, etc. Maybe pandoc may us help here, too. … -
cannot accès to my Model Data base from views.py
I m learning Django 2.2, I am trying to a model from named sKills base on a parent model named Profile: But I have this error : DoesNotExist at /skills/ Profile matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8080/skills/ Django Version: 2.2 Exception Type: DoesNotExist Exception Value: Profile matching query does not exist. in Skills => models.py: from django.db import models from profiles.models import Profile from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class Skill(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) name = models.CharField(max_length=220) score = models.PositiveIntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)]) def __str__(self): return "{}-{}-{}".format(self.user, self.name, self.score) in Skills => Views.py: # Create your views here. def skill_view(request): user_id = request.user.id profile = Profile.objects.get(pk=user_id) #profile = get_object_or_404(Profile, pk=user_id) SkillFormset = inlineformset_factory(Profile, Skill,fields='__all__',extra=1) formset = SkillFormset( instance=profile) context = { 'formset': formset } return render(request,'skills/add.html',context) In Skills => urls.py: app_name = 'skills' urlpatterns = [ path('', skill_view, name='my-skills'), ] In Skills => templates => add.html: {% extends 'base.html' %} {% block title %}my skills{% endblock title %} {% block content %} <form action="" method="POST"> {{formset}} </form> {% endblock content %} I have Profile user in database I do not understand Thanks for your help -
How to Create Model from this Dictionary?
I want to make form Input User from dictionary below but dont know to make it on django my_play = dict( name="may_first_play", hosts='cisco_firewalls', become='yes', become_method='enable', gather_facts='no', tasks=[ dict(action=dict(module='asa_command', commands=['show version','show ip'])), dict(action=dict(module='asa_config', lines=['network-object host 10.1.0.1']) ] ) ihave make model like this but confusing on make on field tasks class Book(models.Model): name = models.CharField(max_length=100) hosts = models.CharField(max_length=100) become = models.CharField(max_length=100) become_method = models.CharField(max_length=100) gather_facts = models.CharField(max_length=100) class task(Book):` Please I will be very grateful if you help me -
Django LOGGING not printing to console and file
I have encountered a strange behavior of Django Loggers. I am developing a front end application using Django. During the login service, I make some requests to certain components and use log.warning() calls to see the flow of the requests. The logs worked perfectly, until I decided to add a LOGGING configuration to print the output of the logs in a file, as I want to deploy the application via Docker and I want to periodically check the log files. When I added the following Django configuration concerning logging: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'detailed': { 'class': 'logging.Formatter', 'format': "[%(asctime)s] - [%(name)s:%(lineno)s] - [%(levelname)s] %(message)s", } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'INFO', 'formatter': 'detailed', }, 'file': { 'class': 'logging.handlers.RotatingFileHandler', 'filename': "{}/am.log".format(BASE_DIR), 'mode': 'w', 'formatter': 'detailed', 'level': 'INFO', 'maxBytes': 2024 * 2024, 'backupCount': 5, }, }, 'loggers': { 'am': { 'level': 'INFO', 'handlers': ['console', 'file'] }, } } The logging stops working. The file specified in the logging configuration, am.log, is indeed created but nothing gets printed to this file. Even the console logging does not take place. I have taken this logging configuration from one of my Django projects for the backend of … -
django has_perm method always return false
im using django 1.11, if i'm calling request.user.has_perm("auth.add_user") in shell, its return true. but if im calling this in a view its return false, all the db permission relations are fine. i tried get_object_or_404 method to get user from db to avoid cache. but its not working # shell >>> user = User.objects.get(pk=497) >>> user.has_perms(["auth.add_user"]) (u'has perm', True) True this is my permission class class DjangoModelPermissionsV2(BasePermission): perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': [], 'HEAD': [], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } authenticated_users_only = True def get_required_permissions(self, method, model_cls): kwargs = { 'app_label': model_cls._meta.app_label, 'model_name': model_cls._meta.model_name } return [perm % kwargs for perm in self.perms_map[method]] def has_permission(self, request, view): if getattr(view, '_ignore_model_permissions', False): return True if request.user and request.user.is_authenticated() or not self.authenticated_users_only: if hasattr(view, 'get_queryset'): queryset = view.get_queryset() else: queryset = getattr(view, 'queryset', None) else: return request.user and request.user.is_authenticated() or not self.authenticated_users_only assert queryset is not None, ( 'Cannot apply DjangoModelPermissions on a view that ' 'does not set `.queryset` or have a `.get_queryset()` method.' ) perms = self.get_required_permissions(request.method, queryset.model) return ( request.user.is_authenticated() and request.user.has_perms(perms) ) # requset.user.has_perms return False settings file REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated … -
how to use custom user model for django-graphql-auth
I am using graphql in my project and want to generate token while registration. Even though django-graphql-auth has all the written mutation, it uses a different user model. But I want to use my custom user model. What should I do?