Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to close flash message in Django
I am developing a sample application using python and Django framework . In this i have shown flash message with cancel [x] icon to close the message using Django Messages Framework in index.html using base.html as (template inheritance). PROBLEM : The problem is although i am able to display the message in index.html , but i cannot cancel it. Below are the code files base.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <title>{% block title %}{% endblock title %} Harry Ice Creams</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#">Harry Ice Creams</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="/about">About Us</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Services </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="/services">Ice Cream</a></li> <li><a class="dropdown-item" href="#">Waffle</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Shake</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link" href="/contact">Contact Us</a> </li> </ul> <form class="d-flex"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> … -
django.db.utils.DatabaseError: file is not a database
Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 411, in execute return Database.Cursor.execute(self, query) sqlite3.DatabaseError: file is not a database The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inn er_run self.check_migrations() File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\core\management\base.py", line 459, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\migrations\loader.py", line 53, in init self.build_graph() File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\migrations\loader.py", line 216, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migratio ns if self.has_table(): File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table tables = self.connection.introspection.table_names(cursor) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\base\introspection.py", line 48, in table_na mes return get_names(cursor) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\base\introspection.py", line 43, in get_name s return sorted(ti.name for ti in self.get_table_list(cursor) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\sqlite3\introspection.py", line 74, in get_t able_list cursor.execute(""" File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\utils.py", line … -
RuntimeWarning: DateTimeField DateClass.date_hour received a naive datetime (2021-01-12 00:00:00) while time zone support is active
Boa noite, estou tentando criar um modelo em django para salvar um DateTimeField, porém apresenta o seguinte erro: RuntimeWarning: DateTimeField DateClass.date_hour received a naive datetime (2021-01-12 00:00:00) while time zone support is active. vi em vários lugares que preciso transformar minha data em ciente do fuso horário, mas não sei como implementar os conceitos que foram apresentados. Alguma dica de como posso resolver essa questão? -
Template class view from URL with variables in it not displaying
I currently am trying to have this class template view render with the variabels in the URL. For example I have http://localhost:8000/confirm/?email=hello@example.com&conf_num=641484032777 as the URL My class view looks like this class Confirm(TemplateView): template_name = 'confirm.html' def get_context(self, request, *args, **kwargs): context = super(Confirm, self).get_context() sub = Newsletter.get(email=request.GET['email']) if sub.conf_num == request.GET['conf_num']: sub.confirmed = True sub.save() context['email'] = request.GET['email'] context['action'] = 'added' else: context['email'] = request.GET['email'] context['action'] = 'denied' return context my urls.py looks like this path('confirm/', views.Confirm.as_view(), name='confirm'), And my confirm.html looks like this <!doctype html> <html> <head> <title> Email Newsletter </title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="col-12"> <h1>Email Newsletter</h1> </div> <div class="col-12"> <p>{{ email }} has been {{ action }}.</p> </div> </div> </body> </html> But for some reason it never displays of updates the email or the action. Any help would be appreciated -
Getting an invalid JWT token when I try to register a django user
trying to figure out why I'm getting an invalid token error given my code below. I'm testing registration and authentication via my API. I create a dummy account and then check my email for the verification link. Everything is working great until I click on the link in the email and receive a 400 bad request and due to my debugging the error is caused by an "Invalid Token". Here is my code: views.py import jwt from django.urls import reverse from django.contrib.sites.shortcuts import get_current_site from django.conf import settings #from rest_framework_simplejwt.views import TokenObtainPairView from rest_framework import generics ,status from rest_framework.response import Response from rest_framework import views from rest_framework.views import APIView from rest_framework_simplejwt.tokens import RefreshToken from rest_framework.permissions import AllowAny from drf_yasg.utils import swagger_auto_schema from drf_yasg import openapi from .models import NewUser from .serializers import RegisterSerializer, EmailVerificationSerializer, LoginSerializer from .utils import ConfirmEmail class CustomUserCreate(generics.GenericAPIView): permission_classes = [AllowAny] serializer_class = RegisterSerializer def post(self, request, format='json'): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data user = NewUser.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('users:email-verify') absurl = 'http://'+current_site+relativeLink+"?token="+str(token) email_body = 'Hi '+user.username + \ ' Use the link below to verify your email \n' + absurl data = {'email_body': email_body, 'to_email': … -
calculate working hours for current week in django
let us consider start time, end time and Break time as def record_working hours(request): records = Records.objects.filter(created_by__client=request.user.client) now = timezone.now() today = timezone.now().date() week_start = today - timedelta(days=(today.weekday())) date_list = [week_start + timedelta(days=x) for x in range(5)] week_last = date_list[-1] working_time = records.filter(date__gte=week_start,date__lte=week_last) for record in records: work_hours = record.start_time - record.end_time - record.break_time return redirect(reverse('record_list')) Hear i need to calculate total working hours for current week but i am getting the error as " type object 'datetime.datetime' has no attribute 'datetime'" and when i print my start time, end time and break time i am getting as start_time = datetime.time(8, 30) end_time = datetime.time(18, 30) break_time = 0.5 -
Get image full url on Django Channel Response
I have created a socket with Django channels that return the serialized data of Category Object. But in the response, there is no full URL(the IP address is not there). This problem is similar to this question Django serializer Imagefield to get full URL. The difference is that I am calling the Serializer from a Consumer(Django Channels). Whereas in the link, Serializer is called from a View. In a Consumer, there is no request object as mentioned in the solution. The Django Channels says that scope in Consumers is similar to request in Views. So how can I get the full image url in this case? -
AttributeError at /tickets/ticket/1/like/ 'str' object has no attribute 'fields'
I have a url that is called when a button is pressed but I am getting an attribute error. The strange thing is I only get the attribute error when I run my app on Heroku, when it is running locally I don't get any errors at all. I have checked and heroku is running my latest code in github so I am really confused as to what is happening here! Traceback: Environment: Request Method: GET Request URL: https://dm-issuetracker.herokuapp.com/tickets/ticket/1/like/ Django Version: 1.11 Python Version: 3.6.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_forms_bootstrap', 'accounts', 'tickets', 'checkout'] Installed 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', 'whitenoise.middleware.WhiteNoiseMiddleware'] Template error: In template /app/templates/base.html, error at line 0 'str' object has no attribute 'fields' 1 : {% load staticfiles %} 2 : 3 : <html> 4 : 5 : <head> 6 : <meta charset="UTF-8"> 7 : <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 : <meta http-equiv="X-UA-Compatible" content="ie=edge"> 9 : <title>IssueTracker{% block page_title %}{% endblock %}</title> 10 : <link rel="icon" href="media/img/bug.jpg"> Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/tickets/views.py" in ticket_vote 71. return … -
How do I upload an image and go to the uploaded image page to change the properties of this model?
I have a list of images, there is a button to upload an image. It is necessary to validate the form in two fields and after successful loading they should get to the page of this image. models.py: class Picture(models.Model): url = models.URLField(blank=True, verbose_name='Ссылка на изображение') image = models.ImageField(upload_to='pictures/%Y/%m/%d', width_field='image_width', height_field='image_height', blank=True, verbose_name='Изображение') image_width = models.IntegerField(default=0, blank=True, verbose_name='Ширина изображения') image_height = models.IntegerField(default=0, blank=True, verbose_name='Высота изображения') is_active = models.BooleanField(default=True, verbose_name='Актуальность изображения') created = models.DateField(blank=True, null=True, default=timezone.now, verbose_name='Дата создания записи') updated = models.DateField(blank=True, null=True, default=timezone.now, verbose_name='Дата ред-ия записи') forms.py: class PictureCreateForm(forms.ModelForm): class Meta: model = Picture fields = ('url', 'image') class PictureChangeForm(forms.ModelForm): class Meta: model = Picture fields = ('image_width', 'image_height') urls.py: urlpatterns = [ path('', views.home, name='home'), path('add_picture/', views.add_picture, name='add_picture'), path('picture_detail/<int:id>/', views.picture_detail, name='picture_detail'), # re_path('picture_detail/(?P<id>[0-9]+)/$', views.picture_detail, name='picture_detail') ] views.py: def add_picture(request, id): if request.method == 'POST': form = PictureCreateForm(data=request.POST, files=request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('home:picture_detail')) else: messages.error(request, 'Ошибка, проверьте данные') else: form = PictureCreateForm() return render(request, 'add_picture.html', locals()) def picture_detail(request, id): picture = get_object_or_404(Picture, id=id) new_form = None if request.method == 'POST': form = PictureChangeForm(data=request.POST) if form.is_valid(): new_form = form.save(commit=False) new_form.picture = picture new_form.save() return redirect('home:picture_detail') else: messages.error(request, 'Ошибка, проверьте данные') else: form = PictureChangeForm() return render(request, 'picture_detail.html', locals()) -
JQuery appendTo working fine but not rendering on the page
im doing some ajax function and everything is working well , im adding clients with their custom form and then sending data to a view how give a JsonResponse so the ajax call is working , but when i wanna add the created client with JQuery its show me on the dev tool that the DIV is added but like nothing is showed on the page like its transparant their is my code and thank you for your help : $(document).ready(function(){ var csrfToken = $("input[name=csrfmiddlewaretoken]").val(); $("#btn-submit").click(function() { var serializedData = $("#ClientForm").serialize(); console.log("hey hey clients!"); $.ajax({ url: $("ClientForm").data('url'), data : serializedData, type: 'post', success: function(response) { console.log(response.client.name) console.log($("#ClientList")) var block ='<div class="heading-section animate-box"> <h2>Client </h2> </div> </div> <div class="col-md-12"> <div class="fh5co-blog animate-box"> <div class="inner-post"> <a href="#"><img class="img-responsive" src="images/user.jpg" alt=""><i class="fa fa-user fa-5x" style="margin: 20px;"></i></a> </div> <div class="desc" style="padding-bottom: 2rem;"> <span class="posted_by"></span> <span class="comment"></a></span> <h3>'+ response.client.name +'</h3> <h3>'+ response.client.email +'</h3> <a href="addexercise.html" class="btn btn-success" style="margin-bottom: 1rem; margin-right: 2rem;">Add / Edit Exercises</a></div> <a href="client.html" class="btn btn-warning" style="margin-bottom: 1rem;">View</a> </div> ' var test = '<h2>'+ response.client.name +'</h2>' var card = '<div class="card mt-2" id="taskCard">'+ response.client.name +'<div class="card-body" ></div></div>'; $(block).appendTo("#clientList") $("#clientList").append(test).html(); } }) $("#ClientForm")[0].reset() }); }); <div class="fh5co-herome"> <div class="fh5co-overlay-5"></div> <div class="fh5co-cover" data-stellar-background-ratio="0" style="background-image: url({% … -
Django PayPal pour l’association d’un envoi de mail automatique
Hi everyone I would like to know how you were able to manage once the customer clicks on the paypal payment button in your Django app, I would like to know how you were able to automatically manage sending an email in his mailbox indeed I can already manage the sending of emails automatically for a button button that I created myself but the case where I used the integration of paypal on the client side, I can't do it -
How to serve static files in django 3.1
I'm use django 3.1 when I have the option DEBUG = True in my settings.py the static files are serve fine, but when I use DEBUG = False the static files are not serve I all ready try with this solution: 404 Static file not found - Django In the answer like in de official docs of django use this: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But still doesn´t works. Someone have any idea why still doesn't works. -
Django urls are the same but I want to call different functions
I have the following URLs file: from django.conf.urls import url from .views import get_tickets, ticket_detail, create_or_edit_ticket, ticket_vote, ticket_vote_list urlpatterns = [ url(r'^$', get_tickets, name='get_tickets'), url(r'^(?P<pk>\d+)/$', ticket_detail, name = 'ticket_detail'), url(r'^(?P<pk>\d+)/$', ticket_vote, name = 'ticket_vote'), url(r'^ticket/(?P<pk>[0-9]+)/like/$', ticket_vote_list, name='ticket_vote_list'), url(r'^ticket/(?P<pk>[0-9]+)/like/$', ticket_vote, name='ticket_vote'), url(r'^new/$', create_or_edit_ticket, name = 'new_ticket'), url(r'^(?P<pk>\d+)/edit/$', create_or_edit_ticket, name = 'edit_ticket') ] and I have my views.py file: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404, redirect from django.utils import timezone from .models import Ticket from .forms import TicketsForm, TicketCommentForm def get_tickets(request): """ Create a view that will return a list of tickets that were published and render them to 'issuetrackertickets.html' template """ tickets = Ticket.objects.filter(published_date__lte=timezone.now ()) return render(request, "issuetrackertickets.html", {'tickets':tickets}) def ticket_detail(request,pk): """ Create a view that will return a single ticket object based on the ticket id and render it to the 'ticketdetail.html' template """ print("ticket detail") ticket = get_object_or_404(Ticket,pk=pk) ticket.views +=1 ticket.save() # Display comments comments = ticket.ticketcomment_set.all().order_by('comment_date') # Form for adding a comment if request.method == 'POST' and request.POST.get('submit'): comment_form = TicketCommentForm(request.POST, request.FILES) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.author = request.user.username comment.ticket = ticket comment.save() return redirect(ticket_detail, pk=ticket.pk) # Form for upvoting tickets elif request.method == 'POST' … -
Django - Export CSV in ManytoMany Field
How to export the name of category on M2M relationship? I've tried to use .all() but return everything wihout format, so is not useful #---------- class Category(models.Model): name = models.CharField(verbose_name='Name', max_length=254) class SubCategory(models.Model): name = models.CharField(verbose_name='Name', max_length=254) category = models.ManyToManyField(Category, blank=True) #---------- from django.http import HttpResponse import csv def csv_export(request): # Get database information qs = SubCategory.objects.all() # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="export_file.csv"' writer = csv.writer(response) writer.writerow(['name','category']) for rule in qs: writer.writerow(['name','category']) return response -
Facing error while using .dat file in Django
I am trying to integrate a deep learning model into my django project and it throws an error saying " can't open shape_predictor_68.dat" . I wrapped my ML code into a function and called it from django rest framework API. What am I missing ? -
How can I send a CSRF token in a form?
I included a Vue form component in one of my Django templates. Now, I would like to send a CSRF token along with the data, since Django views require a CSRF token. Is there any way I can include it in my Vue form? Here is my component: <template> <form @submit.prevent="formSubmit()"> <input type="text" class="form-control" v-model="amount"> <br> <input type="text" class="form-control" v-model="price"> <br> <button class="btn btn-primary" style="width: 100%">BUY</button> </form> </template> <script> import axios from 'axios' export default { mounted() { console.log('Component mounted.') }, data() { return { name: '', description: '', output: '' }; }, methods: { formSubmit() { let currentObj = this; axios.post('MY_URL', { price: this.price, amount: this.amount, }) .then(function (response) { currentObj.output = response.data; }.bind(this)) .catch(function (error) { currentObj.output = error; }); }, } } </script> -
Follow button created with ajax and jQuery not responsive
I'm trying to add a follow feature to my project with ajax views and jquery but the follow button is not responsive. It keeps returning: *127.0.0.1 - - [29/Dec/2020 00:11:47] "POST /account/users/follow/ HTTP/1.1" 404 - Not Found: /account/users/follow/ * whenever I click on the button. Here's my views.py code @ajax_required @require_POST @login_required def user_follow(request): user_id = request.POST.get('id') action = request.POST.get('action') if user_id and action: try: user = User.objects.get(id=user_id) if action == 'follow': Contact.objects.get_or_create( user_from=request.user, user_to=user, ) else: Contact.objects.filter(user_from=request.user, user_to=user).delete() return JsonResponse({'status': 'ok'}) except User.DoesNotExist: return JsonResponse({'status': 'error'}) return JsonResponse({'status': 'error'}) the model's file from django.db import models from django.conf import settings from django.contrib.auth import get_user_model class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True) def __str__(self): return f'Profile for user {self.user.username}' class Contact(models.Model): user_from = models.ForeignKey('auth.User', related_name='rel_from_set', on_delete=models.CASCADE) user_to = models.ForeignKey('auth.User', related_name='rel_to_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ('-created',) def __str__(self): return f'{self.user_from} follows {self.user_to}' # Add following field to User dynamically user_model = get_user_model() user_model.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) then the detail template {% extends "base.html" %} {% load thumbnail %} {% block title %}{{ user.get_full_name }}{% endblock %} {% block content %} <h1>{{ user.get_full_name }}</h1> <div class="profile-info"> <img src="{% thumbnail … -
Django base.models.Post.DoesNotExist
I am very new to django. I have followed the steps from a video on youtube on how to create a simple blog. Basically, I have a portfolio main page that displays several things including the latest blogs. It all works well. I can see the latest posts on the main page. I can also click in each of them and they open up fine. However, now, I want to create a new page (blog.html) that will hold all the posts. I created a blog.html and did the necessary settings in views.py and urls.py. However, for some reason I get an error when trying to access localhost/blog/ This is my urls.py: urlpatterns = [ path('', views.home, name='home'), path('work/', views.work, name='work'), path('<slug:slug>/', views.post_detail, name='post_detail'), path('blog/', views.blog, name='blog'), ] Here views.py: def home(request): posts = Post.objects.all() return render(request, 'home.html', {'posts': posts}) def post_detail(request, slug): post = Post.objects.get(slug=slug) return render(request, 'post_detail.html', {'post': post}) def blog(request): posts = Post.objects.all() return render(request, 'blog.html', {'posts': posts}) And lastly the error: Internal Server Error: /blog/ Traceback (most recent call last): File "C:\Users\frank\Anaconda3\envs\djangoenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\frank\Anaconda3\envs\djangoenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\frank\Anaconda3\envs\djangoenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = … -
Translate many-to-many relationship in database ER diagram to Django model
I want to represent users and teams in Django application. Each user can be member of zero or more teams. This is ER diagram of database that I came up with: Following this design, I'd like to implement Django models: class Team(models.Model): name = models.CharField() created_at = models.DateTimeField(auto_now_add=True) class UserIsMemmberOfTeam(models.model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) But this aproach feels not fitted for Django ORM. I've also thought about: from django.db import models from django.conf import settings class Team(models.Model): name = models.CharField() created_at = models.DateTimeField(auto_now_add=True) members = models.ManyToManyField(settings.AUTH_USER_MODEL) There is new field members, but I think, under the hood, database looks similar to the diagram above. Which aproach is better? Maybe each of them has its own perks? But what if: I'd like to assign each team member some role(s) in given team. In ER diagram, I would design it like that: How should I represent it in Django? This time it looks like I can't use the second approach from above, because there is no model representing member. Should I make MemberHasRole model, or should I make Member model that has roles (many-to-many) field? -
Receiving an Error when a Form is submitted related to cleaned_data
I am trying to submit a Message form for my Django Project but I keep receiving an error: AttributeError at / 'MessageForm' object has no attribute 'cleaned_data' I am not sure what is the reason for getting this error although I revised the https://docs.djangoproject.com/en/3.1/topics/forms/ Here is my views.py def home(request): if request.method == 'POST': #Check Post form = MessageForm(request.POST) if form.is_valid(): data = MessageForm() #Create Relationship with Model data.name= form.cleaned_data['name'] data.email= form.cleaned_data['email'] data.message= form.cleaned_data['message'] data.ip = request.META.get('REMOTE_ADDR') data.save() messages.success(request,'Your Message has been sent, Thank you!') return HttpResponseRedirect('base:home') template_name = 'base/home.html' form = MessageForm() ----------------------other unrelated contexts-------------------- context = { 'form': form, } return render(request, template_name, context) Here is the urls.py urlpatterns = [ path('', views.home,name='home') ] Here is the template.html <form class="form" id="form" method="post"> {% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="form-group"> <input name="name" id="form-name" type="text" placeholder="Your Name" class="form-control input" autocomplete="off"/> <div id="name-error"></div> </div> </div> <div class="col-md-6"> <div class="form-group"> <input name="email" id="form-email" type="email" class="form-control input" placeholder="Your E-Mail" autocomplete="off"> <div id="email-error"></div> </div> </div> </div> <div class="form-group"> <textarea name="message" id="form-message" class="form-control input" rows="7" placeholder="Your Message here ..." autocomplete="off"></textarea> <div id="message-error"></div> </div> <!-- Messages --> {% if messages %} {% for message in messages %} <div class="container"> <div class=" alert alert-{{ message.tags … -
Django 400 when sending request through postman, 200 through curl
Problem: When sending request through postman I get 400 error code, logs: Bad Request: /api/auth/login/ [28/Dec/2020 22:07:10] "POST /api/auth/login/ HTTP/1.1" 400 40 [28/Dec/2020 22:07:10] code 400, message Bad request syntax ('{') [28/Dec/2020 22:07:10] "{" 400 - The weird thing I that when I copy the request from postman and past it in the terminal, as the image below, it works fine: ~$ curl --location --request POST 'http://127.0.0.1:8000/api/auth/login/' \ > --header 'Content-Type: application/json' \ > --data-raw '{ > "username": "admin", > "password": "123456" > }' {"access_token":"...","refresh_token":"..."} Other details: When debugging request.data is empty when sending through postman. I am running django in debug mode. -
Getting this error TemplateDoesNotExist at
this is my Views.py from django.shortcuts import render from django.http import HttpResponse Create your views here. def home(request): return render(request, 'home.html') This is my settings.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'z!pmq9mgbaavz!$1i6afqo&-g4egbsql$81s#eii(qt&16z77f' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'seun.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'seun.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True … -
Blank page due to "for template tag" in Django
My web page was working fine until I added {% for %} in my template file. This is my home.html file <body> <div> <div> {% if not status %} <a href="/gmailAuthenticate" onclick="gmailAuthenticate()" title="Google">Google</a> {% else %} {% for item in contexto %} <p>Your are verified</p> <form id="myform" method="post" action="{% url 'logout' id=item.id %}/?next={{request.path }}"> {% csrf_token %} <input type="hidden" name="name" value="value" /> <a onclick="document.getElementById('myform').submit();">disconnect</a> </form> {% endfor %} {% endif %} </div> </div> </body> And this is my home function def home(request): status = True contexto = CredentialsModel.objects.all() if not request.user.is_authenticated: return HttpResponseRedirect('admin') storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() try: access_token = credential.access_token resp, cont = Http().request("https://www.googleapis.com/auth/gmail.readonly", headers={'Host': 'www.googleapis.com', 'Authorization': access_token}) except: status = False print('Not Found') return render(request, 'index.html', {'status': status}) I´ve checked my errors.log file, but nothing is displayed -
Render JSON data to Flask UI vs Django UI?
My requirement is to find out what is the easiest way to render data to web UI via Flask or Django (easiest one) by thinking I already have sample JSON objects with me. Any suggestions how to do that & what's the best/easy among the Flask vs Django ? Thank you! -
Spyne+Django ValueError have conflicting name using
I trying to use spyne to generate a SOAP server, but have an error. Spyne: ValueError: classes <class CHILD'> and <class 'CHILD'> have conflicting name; the types.py file is: class PARENT(ComplexModel): class Section1(ComplexModel): NAME = String class CHILD(ComplexModel): NAME = String class Section2(ComplexModel): NAME = String class CHILD(ComplexModel): NAME = String type = String Have not way to use same class name? spyne need to decalre on views as json and also declare a complexmodel as python classes, but cant use same name of class, but the application need to be return an xml that have this structure, thanks a lot.