Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django password shows in Form Data (Post/Request)
Good evening, I would like to know if when you submit a POST request to Django with your credentials (username/email and password) is normal/save to have that info open in Form Data (dev tools google -> network -> url). Like that: It's possible to hide that info or at least encrypt? Many thanks in advance! -
Erro when duplicate an instance in django
I want to duplicate an instance of my django class. I saw in the documentation https://docs.djangoproject.com/en/3.1/topics/db/queries/#copying-model-instances that I have to set pk to None and save. But this is the result when I try to clone the instance s1 of Scenario: What should I do? -
Send email with Chart.js and Django
I generate data and create charts using Chart.js and Django. Everything works fine, but now I want to send these charts by email. So I have data like below. labels = ['City1', 'City2', 'City3'] data = [[3,5,8], [12,23,3], [9,1,14]] I created a Mail class which allows me to send an email with message and attachments, but I don't know how can I add chart from Chart.js. So, summarizing, I want to do something like below. def send_mail_witch_chart(): labels = ['City1', 'City2', 'City3'] data = [[3,5,8], [12,23,3], [9,1,14]] mail_body = "create chart from above data" mail = Mail() mail_with_chart = mail.prepare_mail('mail_title', mail_body) mail.send(mail_with_charts) So, could somebody help, how can I create mail_body to pass it to prepare_mail() function -
csrf_token error even when the token is included within the html file and settings.py also has csrf middleware included
Thanks for looking into this! I have this error popping up even if my User registration html file has the token in it. Also settings.py file does have django.middleware.csrf.CsrfViewMiddleware included within it. Error Message : "POST /register/ HTTP/1.1" 403 2513 Forbidden (CSRF token missing or incorrect.): /register/ My views.py file : from django.shortcuts import render from django.contrib.auth import login,authenticate # from django.contrib.auth import UserCreationForm #Gives error from django.contrib.auth.forms import UserCreationForm def register(response): if response.method=='POST': form = UserCreationForm(response.POST) if form.is_valid(): form.save() else: form = UserCreationForm() return render(response,'register/register.html',{'form':form}) register.html file : {% extends 'main/base.html' %} {% block title %} Create an account {% endblock %} {% block content %} <form class="form-group" method="POST"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-success">Register</button> </form> {% endblock %} -
Why do I get CSRF authentication error in Django in certain condition?
Okay, so this is a very weird issue I'm having. I have my Django project, and I tried to log in to admin page with my superuser account. I type in the username and password, and this is where the weird error occurs. After typing in the username, when I type password real quick and HIT ENTER right away, the page stays in the loading process. It keeps on loading in the same page for a while, and I hit the submit button again or hit refresh, I get the CSRF authentication error. And when I click on 'back' on my browser, I get the admin page safely logged in. I know it sounds weird. But when I type in the username and password and then CLICK the submit button instead of hitting enter right away, I get logged in without any issue. In short, it's like this: When I try to log in to the admin page, if I type password real quick and hit enter right away, the page does nothing but keep on loading. It loads like forever so if I hit refresh or click submit button again, I get the CSRF authentication error. But if I … -
Django: how to annotate a list of ids (as slug or string)
I have a many-to-many relationship such as: class SeriesCompletion(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL, related_name='completions',) series = models.ForeignKey( Series, blank=True, null=True, on_delete=models.SET_NULL, related_name='completions', ) which contain one record each time a user completes a series I'm trying to build a custom queryset (within a manager) which will annotate for the series model either a slug ("1-12-52-34") or a string ("1,12,52,34") which contain the ids of all the users which completed the series Basically, I want to do the same as following, but through the manager: user_who_completed_id_list = list(SeriesCompletion.objects.filter( series=obj).values_list('user__id', flat=True)) user_who_completed_ids = ','.join(map(str, user_who_completed_id_list)) user_who_completed_ids_slug = '-'.join(map(str, user_who_completed_id_list)) I been doing tons and tons of tests and of research on the web without any success. Could someone help me out? -
Is there a way to display all current entries to a model in order to save a many to many relationship in Django?
I have two tables called Product and Ticket, with a TicketProduct table between as a many-to-many relationship. When I load the page to create a new Ticket, I need to see every current entry in the Product table, along with an entry for a count value on each product, that will save into the TicketProduct table when I save the new Ticket. I am currently able to display the full information about the ticket using a ticket form, I am able to pass in product information, however, I have not been able to display a listing of all products with a text box that will allow me to enter the count, and save at one time. Right now, my form overwrites the text boxes in my for loop and returns only the last product. What do I need to change in order to display and save this data? Views.py def newTicket(request): if request.method == 'POST': ticketForm = TicketForm(request.POST) if ticketForm.is_valid(): ticket = ticketForm.save(commit=False) ticketForm.user_id = request.user.id ticket = ticketForm.save() invoice_number = ticket.pk return redirect(str(invoice_number) + '/newTicketProduct') else: print(ticketForm.errors) else: ticketForm = TicketForm(initial={'tran_type': 'CH', 'user_id': request.user.id}) ticketForm.user_id = request.user.id model = Ticket return render(request, 'tickets/newTicket.html', {'ticketForm': ticketForm}) forms.py class TicketForm(forms.ModelForm): class … -
Use email created on cpanel - django
i try use email from cpanel in django but it show this error : App 634174 output: smtplib.SMTPSenderRefused: (501, b'<=?utf-8?q?Creative?=>: sender address must contain a domain', '=?utf-8?q?Creative?=') and this is my settings.py email setting : #MY EMAIL SETTING EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = False EMAIL_HOST = "mail.techpediaa.com" EMAIL_HOST_USER = "contact@techpediaa.com" EMAIL_HOST_PASSWORD = "mypass" EMAIL_PORT = 26 i'am using namecheap -
'PosixPath' object is not subscriptable
Using ogrinfo -so I've found the structure of the shapefile and based on this structure I've created a model: from django.contrib.gis.db import models class Villages(models.Model): . . . After that I've created the load.py as mentioned here inside the same directory of models.py: from pathlib import Path from django.contrib.gis.utils import LayerMapping from .models import Villages villages_mapping = { . . . } villages = Path(__file__).resolve().parent / 'gis' / 'villages.shp' def run(verbose=True): lm = LayerMapping(Villages, villages, villages_mapping, transform=False) lm.save(strict=True, verbose=verbose) Then, I try to use load.py: python3 manage.py shell > from geodata import load > load.run() But I see this strange error: Traceback (most recent call last): File "", line 1, in File "/home/maxdragonheart/DEV_FOLDER/Django/Enographiae/enographiae_dev/enographiae/geodata/load.py", line 32, in run lm = LayerMapping(Villages, villages, villages_mapping, transform=False) File "/home/maxdragonheart/DEV_FOLDER/Django/Enographiae/enographiae_dev/devenv/lib/python3.7/site-packages/django/contrib/gis/utils/layermapping.py", line 99, in init self.layer = self.ds[layer] TypeError: 'PosixPath' object is not subscriptable -
Need help in finding the count of an unique group of entries in django models
I have 3 models Customer, Services and Uses. The Uses model contains the customer_id and service_id(service) used by the customer. Now what I want is a list of count on the number of times each different service being used by the customer. For example if services say pool and buffet is being used once and twice i want the answer to be [1,2]. I don't want the count on distinct services used rather i want the count on each particular service. Here are my models class Customer(models.Model): firstname = models.CharField(max_length=15) lastname = models.CharField(max_length=15) #other attributes class Services(models.Model): service_name = models.CharField(max_length=15) price = models.IntegerField() class Uses(models.Model): customer = models.ForeignKey(Customer,on_delete=CASCADE) service_id = models.ForeignKey(Services,on_delete=CASCADE) time_used = models.TimeField(default=timezone.localtime()) This is what I have got which returns the distinct services used. count=Uses.objects.filter(customer_id=customer).values('customer_id','service_id').distinct().count() Need some help please to modify it. -
Page Transition using CSS JS (Vanilla) and Django does not work perfectly
I want to make my own transition animation using Vanilla JS in django Framework But I got some issue the URL page is 127.0.0.1:8080/foo/bar/undefined My CSS .my-transition{ position: fixed; width: 0; left: 50%; top: 0; bottom: 0; right: 0; z-index: 123; background-color: #2C4C3B; transition: 0.5s ease-out; } .my-transition.is-active{ width: 100%; left: 0; } in my JS window.onload = () => { const myTransition = document.querySelector('.transition'); const link = document.querySelectorAll('.anchor-load') setTimeout(() => { myTransition.classList.remove('is-active'); }, 500); for(let i = 0; i < link.length; i++){ const anchor = link[i]; anchor.addEventListener('click', e => { myTransition.classList.add('is-active'); let target = e.target.href; setTimeout(()=>{ window.location.href = target; }, 500); e.preventDefault(); }); } } My HTML template <div class="transition my-transition is-active"></div> ... <ul> <li> <a href="{% url 'home' %}" class="anchor-load">Go to Home</a> </li> <li> <a href="{% url 'about' %}" class="anchor-load">Go to About</a> </li> <li> <a href="{% url 'contact' %}" class="anchor-load">Go to Hell</a> </li> </ul> when I use this code the page is work perfectly But I want to make UX UI more attractive by adding some tag like img or span or div inside the anchor tag for ex. <ul> <li> <a href="{% url 'home' %}" class="anchor-load"> <span> Go to Home </span> </a> </li> <li> <a href="{% url … -
Django new field "JSONField" error - Column does not exist
I created a dummy project just to test the new field JSONField of Django but the column doesn't not appear to be created (I am using Postgresql). class Author(models.Model): name = models.CharField(max_length=50) description = models.TextField() slug = models.SlugField() details = models.JSONField() class Meta: verbose_name = "Author" def __str__(self): return self.name If i go to the database, the column is not created -- screenshot When i go to the admin view page of the table Author i get the following error -- screenshot The error in the admin panel is understandable: you cannot view a column that does not exist. Do you guys have the same error? I can't find this error with JSONField anywhere. Thanks Note: This is my first post. -
DateField filter date range in Django_Filter
Does anybody knows how to apply filter date range using django_filter? I want to filter date range using django filter it is possible? filters.py from django.contrib.auth.models import User from .models import Person import django_filters class UserFilter(django_filters.FilterSet): class Meta: model = Person fields = ['province', 'municipality','barangay','classification','classification','category', 'type_payout','payroll_batch', 'batch_it','paid','paid_by' ] #I havent add date yet views.py def sample(request): datefrom = request.POST.get('datefrom', False) #value name from datefrom dateto request.POST.get('dateto', False) #value name from dateto user_list = Person.objects.all() sample_data = UserFilter(request.POST, queryset=user_list) format = {'benefeciaries':sample_data} return render(request, 'payroll.html', format) models.py class Person(models.Model): date_receive = models.DateField(null=True, blank=True) some other value ...... -
app.autodiscover_tasks() TypeError: autodiscover_tasks() missing 1 required positional argument: 'packages'
I am trying to use celery in my django app. But, I was getting an error, so I copied the code from the book I was following(Django 3 by example). Now, when I run the python manage.py makemigrations command, I get this error: app.autodiscover_tasks() TypeError: autodiscover_tasks() missing 1 required positional argument: 'packages' Here is my celery.py, where the error is: import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings') app = Celery('myshop') app.config_from_object('django.conf:settings') app.autodiscover_tasks() What is the problem? -
Script sql in docker-entrypoint-initdb.d not executed
I try to initialize my postgresql database using sql script in docker-entrypoint-initdb.d folder I have no error message but database is not initialized even if I suppress container and rebuilt what is wrong with my docker-compose.yml file? docker-compose.dev.yml version: '3.7' services: web: restart: always container_name: coverage-africa-web-dev build: context: ./app dockerfile: Dockerfile.dev restart: always command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app:/usr/src/app - ./docker-entrypoint-initdb.d/initdata.dev.sql:/docker-entrypoint-initdb.d/initdata.dev.sql ports: - 8000:8000 env_file: - ./.env.dev -
Data not save on database
In my website when someone register he give some values like 1st name,last name,email, password etc. Which save in auth_User database. I want to make a new model Profile which is child of User model. and its have some new fields. models.py class Profile(User): image = models.ImageField(null=True,blank=True, upload_to="profile/") bio = models.TextField(max_length=255,null=True) address = models.CharField(max_length=255,null=True,blank=True,) mobile_no = models.CharField(max_length=10,null=True,blank=True,) website_url = models.CharField(max_length=255,null=True,blank=True,) facebook_url = models.CharField(max_length=255,null=True,blank=True,) twitter_url = models.CharField(max_length=255,null=True,blank=True,) linkdin_url = models.CharField(max_length=255,null=True,blank=True,) forms.py class UserEditForm(UserChangeForm): email = forms.EmailField(widget=forms.EmailInput(attrs={"class":"form-control"}) ) first_name = forms.CharField(max_length=100,widget=forms.TextInput(attrs={"class":"form-control"})) last_name = forms.CharField(max_length=100,widget=forms.TextInput(attrs={"class":"form-control"})) class Meta: model = Profile fields = ('first_name','last_name','username','email','password','image','address','mobile_no','bio','website_url','facebook_url','twitter_url','linkdin_url') widgets = { "username" : forms.TextInput(attrs={"class":"form-control","placeholder":"write title of your posts"}), "website_url" : forms.TextInput(attrs={"class":"form-control","placeholder":"write title of your posts"}), "facebook_url" : forms.TextInput(attrs={"class":"form-control","placeholder":"write title of your posts"}), "twitter_url" : forms.TextInput(attrs={"class":"form-control","placeholder":"write title of your posts"}), "linkdin_url" : forms.TextInput(attrs={"class":"form-control","placeholder":"write title of your posts"}), # # "title_tag" : forms.TextInput(attrs={"class":"form-control"}), # # "author" : forms.HiddenInput(), # # "image" : forms.Select(attrs={"class":"custom-file"}), # "catagory" : forms.Select(choices=choices,attrs={"class":"form-control"}), "bio" : forms.Textarea(attrs={"class":"form-control"}), } urls.py path('edit_profile/',UserEditView.as_view(),name="editProfile"), views.py class UserEditView(UpdateView): form_class = UserEditForm template_name = 'edit_profile.html' success_url = reverse_lazy('editProfile') def get_object(self): return self.request.user edit_profile.html {% extends 'base.html' %} {% block title %} Edit Profile... {% endblock title %} {% block content %} <style> label[for=id_password],.helptext,#id_password { display: none; } </style> {% if user.is_authenticated %} <h1>Edit … -
Error: (index):186 Uncaught SyntaxError: Invalid shorthand property initializer
I am getting this error while sending my form through Ajax in Django Error: (index):186 Uncaught SyntaxError: Invalid shorthand property initializer in line data= formdata Can you help me figure out the solution. uploadBtn.addEventListener('click', e=>{ e.preventDefault() progressBox.classList.toggle('not-visible', false) var formdata = new FormData() formdata.append('csrfmiddlewaretoken', csrftoken) formdata.append('fileA', FileA.files[0]) formdata.append('a_year', year.value) $.ajax({ type: 'POST', url: '', enctype: 'multipart/form-data', data = formdata, success: function(response){ console.log(response) }, error: function(response){ console.log(response) }, cache: false, contentType: false, processData:false, }) }) -
No Module Found Django while sending mail
When I tried sending mails from my django project, experienced this problem. I tried these commands: from django.core.mail import send_mail send_mail("sub", "body", "test@test.com", ["xyz@gmail.com"]) All the email settings are properly configured and it is running on other systems, but it is showing this error on my Ubuntu 20.04 django project Traceback (most recent call last): File "/usr/lib/python3.8/code.py", line 90, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/home/nishi/nishi/campaignmanager/venv/lib/python3.8/site-packages/django/core/mail/__init__.py", line 51, in send_mail connection = connection or get_connection( File "/home/nishi/nishi/campaignmanager/venv/lib/python3.8/site-packages/django/core/mail/__init__.py", line 34, in get_connection klass = import_string(backend or settings.EMAIL_BACKEND) File "/home/nishi/nishi/campaignmanager/venv/lib/python3.8/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in … -
How to migrate/makemigrations in one app with multiple databases
I'm working on a django project with: One single app Three huge identical mysql databases with historical data One mysql database where I store results from calculations of the historical data I'm struggling with how to makemigrations/migrate when I make changes to the models. With only one database I would simple do something like: $ manage.py makemigrations <app_name> $ manage.py migrate <app_name> 0001 But this creates tables for every model in every database. I've tried to mess around with: $ manage.py migrate <app_name> 0001 --database==<name_of_db> But is this all I should do? I have looked into routers but I don't really understand how to configure one for this case. In short: My goal is to be able to update a model and then only migrate the changes to the relevant databases. In some cases the updated model should migrate to the three identical databases, in other cases the updated model should only migrate to the one unique database. All help would be appreciated! -
Search data in array of json array using django filter
I am using Postgresql DB. I have a JSONField in my Model. Here is the json. object.outer_data = [ { 'end': '20-11-2020 02:01 PM', 'start': '20-10-2020 02:01 PM', 'inner_data': [ { 'type': 'primary', 'id': '2' }, { 'type': 'secondary', 'id': '8' } ] }, { 'end': '', 'start': '20-11-2020 02:01 PM', 'inner_data': [ { 'type': 'primary', 'id': '2' }, { 'type': 'secondary', 'id': '6'}] } ] And I want to find out if this data have a matching key 'dietitianid': '6'. Models.objects.filter(outer_data__dietitians__inner_data__contains=[{'dietitianid': '6'}]) But ofcourse this is wrong as I have to pass the index in which inner_data will be searched. I am looking for this query where I can sort of use a double contains. One for dietitians in outer_data and then for dietitianid in dietitians. Any suggestion would be helpful! Thank you. -
django.db.utils.OperationalError: while deploying to pythonanywhere
django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? -
django built-in authentication system not working with react
I am building a django-react app, using Django to render the templates, Django REST framework for the api endpoints, and React on top of django templates. I am using 'rest_framework.authentication.SessionAuthentication' and I have implemented the authentication routes but django's built-in authentication methods (login, logout, authenticate) only seem to work with the templates rendered by django and not with the React components. By this I mean if i have a view like def home_page(request, *args, **kwargs): print("local USER >>>", request.user) print("local SESSION >>>", request.session) return render(request, 'pages/homepage.html', {}, status=200) and I visit the route after logging in, it would print out both the user and the session object. But for the api views, @api_view(['GET', 'POST']) @permission_classes([IsAuthenticatedOrReadOnly]) def post_list_view(request, *args, **kwargs): print("api USER >>>", request.user) print("api SESSION >>>", request.session) ... I get AnnonymousUser and None even if I'm logged in. When i checked the browser cookies, i found both the csrftoken and sessionid cookies. But if I try a post request, I get 403 Forbidden error with "Authentication credentials were not provided." message. (I have also set withCredentials to true.) And in the request headers there was only the X-CSRFToken header (with the token) but sessionid cookie was missing. At this point, … -
How to check request.user against an unrelated model in Django
My question is a little difficult to explain but I'll try my best. Please ask if anything needs to be clarified. I have three models, Exercise, Area, and Workout: class Exercise(models.Model): name = models.CharField(max_length=100) class Area(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) name = models.CharField(max_length=100) exercise = models.ManyToManyField(Exercise, blank=True) class Workout(models.Model): weight = models.DecimalField(default=0.0) reps = models.PositiveIntegerField(default=0) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE) The user will complete a form that adds objects to Area. They can then go into that object and complete a new form that adds objects to Exercise, which are also attached to the specific area through M2M. In order to display only the exercises that this particular user has created, I have an if statement in the exercise template: {% if area.user.user == request.user %}` {{ exercise.name }} {% endif %} I want the user to now be able to go into the Exercise object and complete a form that adds to Workout. I can achieve this but my question is how can I make sure only the logged in users workouts are displayed? area.user.user has no affect since Area is unrelated to this template and I cannot add a user to the Exercise model. -
Django Admin see and ORM query in admin view
In my django project i have two tables: class A(models.Model): n_code = models.CharField(max_length=2, verbose_name='NazA') n_desc = models.CharField(max_length=50, verbose_name='DescA') class B(models.Model): b_code = models.CharField(max_length=2, verbose_name='NazB') b_descr = models.CharField(max_length=50, verbose_name='DescB') b_surname = models.CharField(max_length=50, verbose_name='surB') b_notes = models.CharField(max_length=50, verbose_name='NotesB') i would , when in my django admin console loock at the A model list items view the fields related to an ORM query with A and B models linked by n_code and b_code fields How can i ask Django to display list of fields based on a query instead of just the field declared in my model? so many thanks in advance -
Do errors in BoundField.errors and BoundField.help_text need to be escaped in a template in Django?
Do errors in BoundField.errors and BoundField.help_text need to be escaped in a template in Django? My guess is yes because both the errors and the help_text are no place for HTML code. However, I am a bit confused after I saw the following two snippets of code in the documentation of Django. Snippet A: {% if form.subject.errors %} <ol> {% for error in form.subject.errors %} <li><strong>{{ error|escape }}</strong></li> {% endfor %} </ol> {% endif %} Snippet B: {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} (Snippet A can be found at near here, and Snippet B can be found near here) For Snippet A, I don't think the escape filter is needed because Django's default template engine escapes the string representation of any variable value by default. For Snippet B, I don't think the safe filter should be used because help_text is no place for any HTML code. Is my understanding incorrect, or are these two snippets of demo code in Django's documentation problematic the ways I indicated?