Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CORS denying access even though I've set CORS_ORIGIN_ALLOW_ALL = True
I've got 2 separate projects and project A needs to access some things from project B. I've already installed CORS on project B but accessing its resources from project A still raises the following error: Access to XMLHttpRequest at 'http://api.example.com/api/spotify/1IJxbEXfgiKuRx6oXMX87e' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. CORS on project B is set to CORS_ORIGIN_ALLOW_ALL = True. Am I missing an additional setting or something? -
djangosaml2 authenticates user but i get anonymous user in my django view
I am using djangosaml2 to authenticate my users. i've been using it for a long time now with no problem. i am currently in the process of upgrading python and django to newer versions and the authentication does not work any more. Using the logs, i see that the authentication in djangosaml2 is successful butin my view, the request.user is anonymous user. Here are the working and none-working libraty versions that i use: Python: 2.7 --> 3.8 Django: 1.9 --> 1.11 djangosaml2: 0.17.2 (in both evns.) pysaml2: 4.0.5 --> 6.5.1 (tested also with 4.0.5) -
ModuleNotFoundError: No module named 'django_backend.todo'
Just started a fresh Django Rest framework project and I'm getting stuck on importing a view (TodoView) in urls.py This is a completely fresh project, all I did was add the model, view and now attempting to add the url. File "C:\Users\Simon\Documents\GitHub\tradingjournal\django_backend\django_backend\urls.py", line 20, in <module> from django_backend.todo.views import TodoView ModuleNotFoundError: No module named 'django_backend.todo' urls.py from django.contrib import admin from django.urls import path from rest_framework import routers from django_backend.todo.views import TodoView router = routers.DefaultRouter() router.register(r'todos', TodoView, 'todo') urlpatterns = [ path('admin/', admin.site.urls), ] views.py from django.shortcuts import render # Create your views here. from rest_framework import viewsets from django_backend.todo.models import Todo from django_backend.todo.serializers import TodoSerializer class TodoView(viewsets.ModelViewSet): serializer_class = TodoSerializer queryset = Todo.objects.all() settings.py """ Django settings for django_backend project. Generated by 'django-admin startproject' using Django 3.0.7. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'n3^zfbj#c&i-9v^8q(%iox!kuy@gy2liy-1b+)q21-g&nwezf(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG … -
ERP- tool to efficiently manage employees with projects - Django
I would like to efficiently schedule my staff on different projects. The employees have different capacities. One works full time, another part time. And the projects have different characteristics aswell. Goal: visualization of employees and projects in a MAtrix form. It is an ERP Does anyone have experience, approaches or a goal-oriented tutorial? I thought that many to many relationship might be a key, but i don´t get it. -
How to integrate CKEditor and Cloudinary in Django?
How to upload images in the Model with RichTextField to Cloudinary from the Django admin panel? -
"Django-insecure" in secret key in settings.py in django
After creating a new project with django-admin startproject my settings.py contain: SECRET_KEY = 'django-insecure <actual secret key>' I've never seen "django-insecure' before in a secret key. What does it mean? -
ImproperlyConfigured: Field name `titleweb_poster` is not valid for model `ContestDetail`
I have wriiten some code here. Please check out all the files. When I filled all the fields from django admin then it's working but when I redirect it with http://127.0.0.1:8000/contest/ then I am getting below error django.core.exceptions.ImproperlyConfigured: Field name `titleweb_poster` is not valid for model `ContestDetail`. Where I did wrong? How can I solve it? -
email already exists while updating user in django rest framework
I was updating the User when faced email already exists crossed my way. how ever i could use the extra_kwargs to overcome the email already exists or phone already exists issue. and then using from django.core.validators import EmailValidator in extra_kwargs as "email": {"validators": [EmailValidator]}.. bring back my email field validations. but that don't seems as a real solution. As we are just updating the existing model object.. why It's behaving like we are creating a new one. I think there should be something as defining update or partial_update or i don't know what ever.. is there any other solutions for this ?? class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "id", "full_name", "gender", "phone", "email", "date_of_birth" extra_kwargs = { # "phone": {"validators": []}, # "email": {"validators": [EmailValidator]}, } -
Django dark mood
I'm using django i added dark mood to my website. But only for logged in users, is there a way to add it for anonymous users? Code: class Mood(models.Model): user = models.ForeginKey(User, null=True, blank=True, related_name=dark) Anf i check if it exists in template views function: dark = Mood.object.filter(user=request.user) Context={'dark':dark} Then I check for it i template {% if dark %} add css file for dark mood {%else%} Css light mood file {%endif%} Now the only way to add dark mood is for logged in users, is there another way to do it for anonymous ones? -
Django: How to implement transaction rollback in database if there is insertion in more than one model consecutively?
I am pretty new to Django and I have searched for this topic on the internet but I am not understanding. Basically, I am creating a student user which will be linked to the built-in User model in Django. In my code, I create the user in the user model first then I create it in the StudentUser model. However, if ever an error occurs, maybe the StudentUser was not created, I want to undo the changes in user. How to go around this with rollback? Here is my code snippet: views.py def user_signup(request): if request.method == 'POST': # Signup for student if(request.POST['stud_fname']): stud_fname = request.POST['stud_fname'] stud_lname = request.POST['stud_lname'] stud_uni = request.POST['stud_uni'] stud_email = request.POST['stud_email'] stud_password = request.POST['stud_passwd'] try: user = User.objects.create_user(first_name=stud_fname, last_name=stud_lname, username=stud_email, password=stud_password) StudentUser.objects.create(user=user, university=stud_uni, user_type="Student") messages.success(request, "Account successfully created. You can now log in") return redirect('login') except: messages.error(request, "Failed to create account. Try again!") return render(request, 'signup.html') else: return render(request, 'signup.html') -
Target WSGI cannot be loaded as Python module
How to solve these errors ? Thank you very much for your help. [Sat Apr 24 06:58:37.647922 2021] [:error] [pid 1430] [remote 172.31.12.184:248] mod_wsgi (pid=1430): Target WSGI script '/opt/python/current/app/greatkart/wsgi.py' cannot be loaded as Python module. [Sat Apr 24 06:58:37.648302 2021] [:error] [pid 1430] [remote 172.31.12.184:248] File "/opt/python/current/app/greatkart/settings.py", line 120, in [Sat Apr 24 06:58:37.648305 2021] [:error] [pid 1430] [remote 172.31.12.184:248] 'HOST': os.environ['RDS_HOSTNAME'], wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'greatkart.settings') application = get_wsgi_application() settings.py # Database Configuration if 'RDS_DB_NAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } requirements.txt asgiref==3.2.10 certifi==2020.12.5 chardet==4.0.0 Django==3.1 django-admin-honeypot==1.1.0 django-admin-thumbnails==0.2.5 django-session-timeout==0.1.0 idna==2.10 Pillow==8.2.0 psycopg2-binary==2.8.6 python-decouple==3.4 pytz==2020.1 requests==2.25.1 six==1.15.0 sqlparse==0.3.1 urllib3==1.26.3 db-migrate.config container_commands: 01_migrate: command: "django-admin.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: greatkart.settings django.config option_settings: "aws:elasticbeanstalk:container:python": WSGIPath: "greatkart/wsgi.py" "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "static/" config.yml branch-defaults: main: environment: django-env-4 group_suffix: null environment-defaults: django-env: branch: null repository: null seast-kart-env: branch: null repository: null global: application_name: django-tutorial-4 branch: null default_ec2_keyname: aws-eb default_platform: Python 3.6 default_region: us-west-2 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: git workspace_type: Application -
Optimize multiple Django Autocomplete Light Views to one View- Django
I am using django-autocomplete-light widget for loading data dynamically to display in the forms. I want to optimize below urls to one url and views classes to single view for all the models as most of the code (90%) is common across all the views, only model name and query is different. Here are my urls: path('locations/', views.LocationAutocomplete.as_view(), name='location-autocomplete'), path('societies/', views.SocietyAutocomplete.as_view(), name='society-autocomplete'), path('propcats/', views.PropertyCategoryAutocomplete.as_view(), name='propcat-autocomplete'), ... path('projects/', views.ProjectAutocomplete.as_view(), name='project-autocomplete'), Here are its Views: class PropertyCategoryAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return PropertyCategory.objects.none() enquiry_flag = self.request.session.get('enquiry_flag', 3) qs = PropertyCategory.objects.filter(type__enq_code = enquiry_flag) if self.q: qs = qs.filter(name__istartswith=self.q) return qs class LocationAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return Location.objects.none() qs = Location.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class FloorAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return Floor.objects.none() qs = Floor.objects.all() if self.q: qs = qs.filter(floor__istartswith=self.q) return qs class ProjectAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return Project.objects.none() qs = Project.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class SocietyAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return Society.objects.none() preferred_area = self.forwarded.get('preferred_area', None) qs = Society.objects.filter(location_id__in=preferred_area) if self.q: qs = qs.filter(name__istartswith=self.q) return qs I was trying to something like this, but not sure how can I pass other relevant parameters such as query parameters, model … -
I want value instead of id in django after left join
Hi i have three tables in models.py and i perform Left Join. When i render data in template after join i get job_no as id instead of value. Can u help me to get the original value instead of id. class Job(models.Model): job_no = models.CharField(max_length=200) class RecievableInvoice(models.Model): invoice_no = models.CharField(max_length=200) invoice_amount = models.IntegerField() job_no = models.ForeignKey(Job,on_delete=models.CASCADE) class PayableInvoice(models.Model): invoice_no = models.CharField(max_length=200) invoice_amount = models.IntegerField() job_no = models.ForeignKey(Job,on_delete=models.CASCADE) And here is my query cursor.execute(''' Select RecievableInvoice.job_no,RecievableInvoice.invoice_no,RecievableInvoice.invoice_amount, PayableInvoice.invoice_no,PayableInvoice.invoice_amount, FROM RecievableInvoice LEFT JOIN PayableInvoice ON RecievableInvoice.job_no = PayableInvoice.job_no''') Screenshot Attached -
How do I keep the current user for a child form from a formset?
I don't fully understand the logic. In my model, the attachment has an author, and the post also has an author. But, I need to save two current users in Post and Attachment. But only the current user is saved to the form, and not saved to the formset. class PostCreateView(CreateView): model = Post template_name = 'modules/post/post_create.html' form_class = PostForm success_url = None def get_context_data(self, **kwargs): data = super(PostCreateView, self).get_context_data(**kwargs) if self.request.POST: data['formset'] = PostAttachmentFormSet(self.request.POST) else: data['formset'] = PostAttachmentFormSet() return data def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): form.instance.created_by = self.request.user formset.instance.created_by = self.request.user #not working... self.object = form.save(commit=False) form.save_m2m() if formset.is_valid(): formset.instance = self.object formset.save() return super(PostCreateView, self).form_valid(form) def get_success_url(self): return reverse_lazy('main') -
Adding github database to a Django project
from django.http import HttpResponse from django.shortcuts import render import hashlib, bcrypt from urllib.request import urlopen, hashlib import time def main(request): return render(request,'main.html') def HashBrut(request): sha1hash = request.POST.get('decoder','default') LIST_OF_COMMON_PASSWORDS =str(urlopen('https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/Common-Credentials/10-million-password-list-top-10000.txt').read(), 'utf-8') time.sleep(5) I am trying to access this"LIST_OF_COMMON_PASSWORDS" from github inside my django project. The python functions works fine in terminal but when i use it inside my views.py file in Django project and try to execute it on the web file, it gives 'A server error occurred. Please contact the administrator.' error. I am new to Django and i don't know what is going wrong. -
How to modify existing data in database on the admin site
from django.contrib import admin from .models import Types @admin.register(Types) class TypesAdmin(admin.ModelAdmin): list_display = [x for x in list(Types._meta._forward_fields_map.keys())] search_fields = ['firsts', 'seconds'] list_filter = ['firsts'] I can only add data, but I can't modify existing data on the admin site. I can only add data, but I can't modify existing data on the admin site. -
Bootstrap4 Custom file input with django-crispy-forms?
I´d like to reproduce the 'custom file input' layout with Django-crispy-forms. Here is the Bootstrap4 custom file input: https://getbootstrap.com/docs/4.0/components/input-group/#custom-file-input <div class="input-group mb-3"> <div class="custom-file"> <input type="file" class="custom-file-input" id="inputGroupFile02"> <label class="custom-file-label" for="inputGroupFile02">Choose file</label> </div> <div class="input-group-append"> <span class="input-group-text" id="">Upload</span> </div> </div> I guess I need to use AppendedText from Django-crispy-forms but I don't get how to do it. -
Unable to add field to Django model
I have the following model: class HadesUser(models.Model): # Database attributes user_id = models.BigAutoField(primary_key=True) django_user = models.OneToOneField(User, on_delete=models.PROTECT, null=False) is_active = models.BooleanField(default=True) created_by = models.ForeignKey('HadesUser', on_delete=models.PROTECT, null=True, db_column='created_by', related_name='%(class)s_created_by') created_datetime = models.DateTimeField(default=datetime.now, blank=True) last_modified_by = models.ForeignKey('HadesUser', on_delete=models.PROTECT, null=True, db_column='last_modified_by', related_name='%(class)s_last_modified_by') last_modified_datetime = models.DateTimeField(default=datetime.now, blank=True) Now I want to add a new field, should be easy, right? So I add: timezone = definition_name = models.CharField(max_length=30, default='UTC', blank=True) Then I just run: python manage.py makemigrations However, I get: (venv) E:\HadesAPI>python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: HadesAPI.HadesUser.timezone: (models.E006) The field 'timezone' clashes with the field 'timezone' from model 'HadesAPI.hadesuser'. This error message is so super not clear at all. I am not using "timezone" anywhere, what could be the issue here? -
Coverage test shows the same result
I want my models.py and views.py coverage test percent above 95 however it's been the same over changes that I've made on the tests.py and also most parts of my code in tests.py are shown as missed and they are red even the setUp part and I haven't been successful to realize where the problem is. any help would be highly appreciated models.py import datetime from django.db import models class Author(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) date_of_birth = models.DateField() date_of_death = models.DateField(null=True) def is_alive(self): return self.date_of_death is None def get_age(self): if self.date_of_death is None: return datetime.date.today() - self.date_of_birth else: return self.date_of_death - self.date_of_birth def __str__(self): return f'{self.first_name} {self.last_name}' class Book(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey(Author, on_delete=models.CASCADE) summary = models.TextField() date_of_publish = models.DateField() def get_age(self): return datetime.date.today() - self.date_of_publish def __str__(self): return self.title views.py from django.shortcuts import render from library_management.models import Book def booklist(request, author_age, book_age): books = Book.objects.all() good_books = [] bad_books = [] for book in books: if book.get_age().days // 365 < book_age: if book.author.get_age().days // 365 < author_age: good_books.append(book) else: bad_books.append(book) else: bad_books.append(book) return render(request, 'booklist.html', { 'good_books': good_books, 'bad_books': bad_books }) tests.py from django.test import TestCase from library_management.models import Author, Book def Test_class(TestCase): def setUp(self): … -
Using Latex in Djngo project with django_tex , pdflatex
I am trying to use Latex to build PDFs in Django project using django_tex , pdflatex. I have made setting such that in django setting.py , under INSTALLED_APPS, TEMPLATES . When server started running and the method is called , it is throwing an error while compiling the latex file . Command 'cd "/tmp/tmpvk2or_tb" && pdflatex -interaction=batchmode texput.tex' returned non-zero exit status 127. is the error. I am attaching my code part in Views.py and also my latex file . Views.py from django_tex.shortcuts import render_to_pdf template_name = 'test.tex' context = {'content':'this is the pdf content'} return render_to_pdf(request, 'test.tex', context, filename='test.pdf') test.tex \documentclass{article} \begin{document} \section{ {{ content }} } \end{document} Can someone suggest something on this . And Is latex is the better option to generate pdfs with all backgrounds and all than using xhtml2pdf ? Thanks in advance -
How do I Save and create Two Model user at same time in django?
I have following models Users and Teacher User model is inherited from AbstractBaseUser and Teacher is one to one relation with User. Below is Teacher User Model. class TeacherUser(BaseModel): user = models.OneToOneField(User, on_delete=models.CASCADE, ) faculty = models.CharField(max_length=100) faculty_code = models.CharField(max_length=100) is_full_time = models.BooleanField(default=False) joined_date = models.DateField() objects = TeacherUserManager() Now problem is I want the only one form to be filled by teacher while registering the teacher user.So I tried this in TeacherSerialzier. class CreateTeacherUserSerializer(TeacherUserSerializer): class Meta(TeacherUserSerializer.Meta): fields = ( 'faculty', 'faculty_code', 'is_full_time', 'joined_date' ) class CreateUserSerializer(UserSerializer): techer = CreateTeacherUserSerializer(source='teacheruser') class Meta(UserSerializer.Meta): fields = ( 'username', 'fullname', 'email', 'phone_number', 'password', 'techer' ) extra_kwargs = { 'password': { 'write_only': True, 'style': {'input_type': 'password'} } } The default form given is as below (image). Now on my views.py I tried creating my user and teacher users class CreateUserView(generics.CreateAPIView): serializer_class = serializers.CreateUserSerializer permission_classes = (AllowAny,) def perform_create(self, serializer): return usecases.CreateUserUseCase(serializer=serializer).execute() and The main logic section where I tried creating users is as below usecases.py User = get_user_model() class CreateUserUseCase: def __init__(self, serializer): self._serializer = serializer self._data = serializer.validated_data def execute(self): self._factory() def _factory(self): teacher_user = self._data.get('teacheruser') By default when I fill the above image form I get ordered dictionary and there comes another … -
View with different filter django
I have this view class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username = self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') Where I show all posts by a User on a page. I would like to add filters on in my 'side menu', to show on same page only posts by that user AND a selected status. Like below: class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username = self.kwargs.get('username')) return Post.objects.filter(author=user, status='Reported').order_by('-date_posted') How can I make 'status' a variable which would be changed my bootstrap button? So what a user choose in a radio or dropdown menu will be a type os 'status' and only that one will be shown. Do I need to call a function each time or? -
how to show current user login posts show in dashboard in django
I am trying to show only login user posts show in the dashboard. Tell me how to show posts in the dashboard. this is my code and how to solve my problem tell me. form.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','decs'] labels = {'title': 'Title', 'decs': 'Decription'} title = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control',})) decs = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control',})) views.py def dashboard(request): if request.user.is_authenticated: current_user = request.user posts = Post.objects.filter(user=current_user) else: redirect('/login/') return render( request, "dashboard.html", {'posts':posts} ) Models.py class Post(models.Model): title = models.CharField(max_length=100) decs = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def get_absolute_url(self): return reverse('author-detail', kwargs={'pk': self.pk}) Dashboard.html <h3 class="my-5">Dashboard </h3> <a href="{% url 'addpost' %}" class="btn btn-success">Add Post</a> <h4 class="text-center alert alert-info mt-3">Show Post Information</h4> {% if posts %} <table class="table table-hover bg white"> <thead> <tr class="text-center"> <th scope="col" style="width: 2%;">ID</th> <th scope="col" style="width: 25%;">Title</th> <th scope="col" style="width: 55%;">Description</th> <th scope="col" style="width: 25%;">Action</th> </tr> </thead> <tbody> {% for post in posts %} <tr> <td scope="row">{{post.id}}</td> <td>{{post.title}}</td> <td>{{post.decs}}</td> <td class="text-center"> <a href="{% url 'updatepost' post.id %}" class="btn btn-warning btn-sm">Edit</a> <form action="{% url 'deletepost' post.id %}" method="post" class="d-inline"> {% csrf_token %} <input type="submit" class = "btn btn-danger btn-sm" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> {% else %} <h4 class="text-center … -
I got error when I turn DEBUG true on settings file
I got Error500 when I turn DEBUG True on settings.py but everything is okay when DEBUG is False. python manage.py collectstatic is okay too. Here my settings.py. I will appreciated your help. I use Django 2.2 version. Django settings """ Django settings for samamarche project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import dj_database_url import os import django_heroku -
REST API taking too much time to respond
I have built an API using Django & django-rest-framework. The Django Server is currently deployed on Heroku's Free Hobby Dyno. this is how my API call looks right now, GET https://feasta-postgres.herokuapp.com/menu/get_category/?admin_id=5 I am currently testing my API through POSTMAN. PROBLEM I have noticed that when I call this API for the First time, it takes too much (~1 second) time to respond. Then it becomes Faster for the subsequent calls. Then after some interval it again becomes slow. This is the event waterfall for my first request call, This is the event waterfall for my subsequent request calls, As we can see in the first image, the handshakes are eating up most of the time. Questions Is there any way to optimize the first request? If yes then How? Will this also occur when I call this API from a Deployed React website or is this only a Postman problem? My Best Guess I am using a Free Heroku Dyno, that's why Heroku is being "lazy" to process my request. Upgrading it to the paid one will do my job.