Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrap : badge over an image instead of under it
I'm trying to put a little badge of colour over an image of a product with Bootstrap. Things were working well but I had to change the image to be of class embed-responsive in order to have the images of all products the same size. And now the badge cannot be seen anymore. I think this is because the badge is now under the image. Any idea how I can solve that ? Here is my code : <div class="list-card-image"> <div class="embed-responsive embed-responsive-16by9"> <div class="star position-absolute" ><span class="badge badge-success">Cuisiné par {{ plat.chef }}</span></div> <a href="{% url 'display' plat.id %}"> <img src="{{ plat.photo.url }}" class="img-fluid item-img embed-responsive-item" width="100%" height="100%"></a> </div> </div> Thanks in advance ! -
Convert postgres (.pgsql) data file to sqlite3 (db.sqlite3) on Ubuntu
I need to convert a postgres file into sqlite3 database file. I already have data in popstgres db. This is related to Django-webapp. Is it possible and if yes, how? -
InlineFormset Factory Dile Upload Form
I am trying to make an inlineforms through django. I have made a model to save the uploaded Image. Unfortunately the image is not getting uploaded through the form. I am not able to track why the image is not getting saved in the folder. models.py - This file contains all the models. class courses(models.Model): name = models.CharField(max_length = 50) class topics(models.Model): name = models.CharField(max_length = 50) sno = models.PositiveIntegerField(default = 0) course = models.ForeignKey(courses,on_delete = models.CASCADE,null = True) class sub_topics(models.Model): name = models.CharField(max_length = 50) content = models.TextField(null = True) sno = models.PositiveIntegerField(default = 0) image = models.ImageField(upload_to=('images/'),blank= True,null = True) topic = models.ForeignKey(topics,on_delete = models.CASCADE,null = True) forms.py - In this file through the inlineformset_factory I have made courses->topics->sub_topics data base structure. The sno is use to store the serial number of the child forms TopicFormset = inlineformset_factory(courses, topics, fields=('name','sno'),extra =1,widgets = {'sno': HiddenInput()}) Sub_TopicFormset = inlineformset_factory(topics, sub_topics, fields=('name','content','sno','image'),extra = 1,widgets = {'sno': HiddenInput()}) views.py - In this file I have used CreateView to display the forms created. While saving the results the Course and Topics are saved but while saving the subtopic only the character input is getting saved. The image is not getting saved Even after … -
Django REST Framework - Reference to the User who added the order
I am creating an application in Django REST Fremework, in which the user can add an order. I would like the serializer to set a reference to the user based on the token and complete the "Client" model field. It's actually works with HiddenField, as shown in the documentation. (Link: https://www.django-rest-framework.org/api-guide/fields/#hiddenfield) class OrderSerializer(serializers.ModelSerializer): client = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Order fields = '__all__' The problem is that when I fetch a single order or list of orders, Client field is of course hidden becouse of HiddenField type. curl -X GET http://127.0.0.1:8000/api/orders/12 { "id":12, "name":"sprzatanie ogrodka", "description":"dupa", "price":"12.20", "work_time_hours":2, "work_time_minutes":50, "workers_needed_num":3, "coords_latitude":"-1.300000", "coords_longitude":"1.100000", "created_at":"2020-03-08T13:20:16.455289Z", "finished_at":null, "category":1, "workers":[] } I would like the field to still capture reference to the logged in user, but at the same time to be visible when returning data from the API. What serializers field type I need to use? Thanks! -
Django models textchoice error while insert value
I'm trying to create a model with choice text as string for postgres varchar(10) models.py from django.utils.translation import gettext as _ from django.contrib.auth.models import User from django.db import models class File(models.Model): users = ( (str(user), str(user)) for user in User.objects.all() ) file_name = models.CharField(max_length=50) file_type = models.CharField(max_length=10) file_upload = models.FileField(upload_to ='uploads/') file_published_date = models.DateTimeField() file_uploaded_by = models.CharField(choices=users) I'm getting error at 'file_uploaded_by': Exception Type: TypeError at /admin/sftp/file/add/ Exception Value: '>' not supported between instances of 'int' and 'NoneType' -
Django static files dont find
i wrote this and my static files don't load my settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') my urls.py urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) error [08/Mar/2020 16:51:18] "GET /static/bootstrap/bootstrap.min.css HTTP/1.1" 404 1808 thank you in advance -
Images aren't being uploaded in django and showing up error 404
I am a newbie in django and making a trial blog for practice. I am getting an error regarding the images uploaded: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/media/default.jpg Raised by: django.views.static.serve "E:\Django\boot\media\default.jpg" does not exist the default.jpg is in the correct directory but am still getting this error. Also, if i upload an image, i can view it in django admin page but its not showing up in the actual webpage. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from PIL import Image class Post(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) pic = models.ImageField(default="default.jpg",upload_to="images") title = models.CharField(max_length=200) sub_title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) content = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse('detail',kwargs = {'pk':self.pk}) forms.py from .models import Post from django import forms class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','sub_title','content','pic') views.py from django.shortcuts import render from .models import Post from .forms import PostForm from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) class PostListView(ListView): model = Post template_name = "blog/index.html" context_object_name = "posts" class PostDetailView(DetailView): model = Post class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = PostForm template_name = … -
API endpoint returns TypeError: 'type' object is not iterable
I am writing a create user API by extending the class users with AbstractBaseUser class. The API was working fine for regular model fields like EmailField, CharField, BooleanField. But then I decided to store the profile_picture of users as well. So I create a new field profile_picture as ImageField to store the path of user's profile picture in the same extended users model. models.py class Users(AbstractBaseUser, PermissionsMixin): """ This model is used to store user login credential and profile information. It's a custome user model but used for Django's default authentication. """ email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=False, null=False) last_name = models.CharField(max_length=255, blank=False, null=False) profile_picture = models.ImageField(upload_to='Images/', max_length=None, blank=True) is_active = models.BooleanField(default=True) # defing a custome user manager class for the custome user model. objects = managers.UserManager() # using email a unique identity for the user and it will also allow user to use email while logging in. USERNAME_FIELD = 'email' Then I updated UserAPIView class to add parser_classes = (FileUploadParser) view.py from django.shortcuts import render from . import views from rest_framework.views import APIView from django.db import IntegrityError from rest_framework import status from . import models, serializers from rest_framework.response import Response from django.core.mail import send_mail from rest_framework.parsers import … -
How to allow users edit thier profile?
I'm new to Django Framework and trying to learning it by making a website which users can post . I want to allow users to edit their profile after registration but the tutorials i found online was not straight forward and complicated . like these two : https://www.youtube.com/watch?v=D9Xd6jribFU https://www.youtube.com/watch?v=CQ90L5jfldw I would appreciate it if someone help me with this Thank you -
Django-sekizai not working despite following the documentation
I followed every step of the documentation to setup my project, but I can`t seem to get it working. Here`s the code: base.html {% load sekizai_tags %} <html> <body> <h1>I`m the base</h1> {% block content %}{% endblock %} {% block js %}{% endblock %} {% render_block "js" postprocessor "compressor.contrib.sekizai.compress" %} </body> </html> test.html {% extends "base.html" %} {% load sekizai_tags %} {% block content %} {% include "include.html" %} {% endblock %} {% block js %}{% addtoblock "js" %} {{ block.super }} <script> alert("Outer") </script> {% endaddtoblock %}{% endblock %} include.html {% load sekizai_tags %} I`m included {% block css %}{% addtoblock "css" %} <script> alert("Inner") </script> {% endaddtoblock %}{% endblock %} When I render that page, I can see Im the baseandIm included. The alert Outer gets fired but not the Inner. What should I do to also let the inner alert fire? -
Why doesn't migration work for foreign key in Django?
so I'm using Django to create a blog. To clarify who the author of an article is, I've added a foreign key in models.py class EachArticle(models.Model): # title, body, and so on userKey = models.ForeignKey(User, default=None, on_delete=models.CASCADE I've done the makemigrations and migrate command, but then I get this error that there is no column named 'userKey_id' in my 'eacharticle' relations. Why does this error occur? and why does it look for a column named 'userKey_id', when the field I added is 'userKey'? + I've checked the table in my Posgres, and realized there is no column named 'userKey', as well as 'userKey_id' apparently. I would very much appreciate your help :) -
Django TemplateSyntaxError: Could not parse the remainder: '"{%' from '"{%'
I am trying to do cycle inside the for loop but it raises error. What is the correct alternative. {% cycle "{% include 'col-1-of-3.html' %}" "{% include 'col-2-of-3.html' %}" "{% include 'col-3-of-3.html' %}" %} Error: TemplateSyntaxError: Could not parse the remainder: '"{%' from '"{%' -
How to update infromation on web page without refreshing the web page in django?
I have a Django model form connected to a MySQL database. Using model_name.objects.all(), I display all the names stored in the database on a different webpage (names = input from the user using Django forms). What I want to do is, when I change the names in the MySQL database it should update on the webpage without refreshing it. I know that I need to send a GET request to the database using AJAX, however, I do not know how to implement it in the code since I do not know JQuery or Javascript. I am also fairly new to Django and learning. Thank you for helping me out. My views.py is def up(request): allmodels = Newmodel.objects.all() context = {'allmodels':allmodels} return render(request, 'up.html', context) My up.html is <body> {% for models in allmodels %} <td> <li> {{models}} </li> </td> {%endfor%} </body> -
'HTTP status code must be an integer' error in Django view
i have small scraping view in my Django website, but i get an error 'HTTP status code must be an integer' in line: 'return HttpResponse(request, 'scrapingscore.html', {'original_link':original_link}) ' def scraping(request): rootlink = 'https://www.transfermarkt.pl' link = 'https://www.transfermarkt.pl/schnellsuche/ergebnis/schnellsuche?query=' if request.method == 'POST': data = request.POST.get("textfield") if data == '': empty = 'Data is empty' return HttpResponse(request, 'scrapingscore.html', {'empty':empty}) else: data = data.replace(" ", "+") search = link + data + '&x=0&y=0' req = Request( search, data=None, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36' } ) req = urlopen(req).read() soup = BeautifulSoup( req, features="lxml" ) anchor = soup.find("a",{"class":"spielprofil_tooltip"}) link = anchor.get("href") original_link = rootlink + link return HttpResponse(request, 'scrapingscore.html', {'original_link':original_link}) return render(request, 'scraping.html') I don't know why i get an error 'HTTP status code must be an integer'. I have one argument in dict in this line with error and i don't know how to repair it, i thought it will work but it is not. When user input is blank, i also get this error in line 'return HttpResponse(request, 'scrapingscore.html', {'empty':empty})'. -
Can't use validation error for a form in django
I have a birthday field in a model and when i try to validate the form i want it so that the age should be 13+ to validate the form . I have set up something like this .forms.py class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=60, help_text='Add a valid email') today = date.today() class Meta: model = Account fields = ('email','username', 'password1', 'password2', 'first_name','last_name','addresse','birthday','city','profil_pic') def clean_birth(self): birthday = self.cleaned_data['birthday'] if int((today-birthday).days / 365.25) < 18: raise forms.ValidationError("Users must be 18+ to join the website")` template <form method="post"> {% csrf_token %} {{registration_form.as_p}} {% if registration_form.errors %} {% for field in registration_form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in registration_form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} <button type="submit">zef</button> </form> But this only show the main errors of django like wrong email and passwords not matching -
HeaderParseError Invalid Domain
I am getting this error when i try to invoke an email to be sent to an Admin when a staff applies for leave. Below are my email settings and the server stack trace. Any thoughts why am getting this and how to fix it, thanks. email settings: EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'jacmuhuri@gmail.com' #test EMAIL_HOST_PASSWORD = '*******'#test EMAIL_PORT = 587 EMAIL_USE_TLS = True stacktrace: Internal Server Error: /dashboard/leave/apply/ Traceback (most recent call last): File "C:\Users\hp\Anaconda3\envs\hrenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Projects\hr_app\humanresource\src\dashboard\views.py", line 575, in leave_creation leave_application_email(leave_obj=instance) File "C:\Projects\hr_app\humanresource\src\leave\emails.py", line 85, in leave_application_email template="leave_application", File "C:\Projects\hr_app\humanresource\src\leave\emails.py", line 61, in send_email return msg.send(fail_silently=True) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\site-packages\django\core\mail\message.py", line 291, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\site-packages\django\core\mail\backends\smtp.py", line 110, in send_messages sent = self._send(message) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\site-packages\django\core\mail\backends\smtp.py", line 122, in _send from_email = sanitize_address(email_message.from_email, encoding) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\site-packages\django\core\mail\message.py", line 119, in sanitize_address address = Address(nm, addr_spec=addr) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\email\headerregistry.py", line 42, in __init__ a_s, rest = parser.get_addr_spec(addr_spec) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\email\_header_value_parser.py", line 1631, in get_addr_spec token, value = get_domain(value[1:]) File "C:\Users\hp\Anaconda3\envs\hrenv\lib\email\_header_value_parser.py", line 1604, in get_domain raise errors.HeaderParseError('Invalid Domain') email.errors.HeaderParseError: Invalid Domain -
Django Teamplate Error name 'Post_title' is not defined
I'm trying to render index HTML and get post title from database but I'm getting error. I define in views post database but still getting error name 'Post_title' is not defined my app/views.py from django.shortcuts import render, get_object_or_404 from django.shortcuts import reverse from .models import BlogPost,comments def index(request): Post_list = BlogPost.objects.all() template_name = 'front/index.html' return render(request, template_name,{Post_title:"Post_title",}) def post_detail(request): return render(request, 'front/post_detail.html') my app/urls.py from django.urls import path from .import views urlpatterns = [ path('', views.index, name = 'index'), path('<int:BlogPost_id>/', views.post_detail, name='Post Detail') ] my project/urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static from froala_editor import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('froala_editor/', include('froala_editor.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my index.html template <div class="col-md-8 mt-3 left"> {% for post in Post_list %} <div class="card mb-4"> <div class="card-body"> <h2 class="card-title">{{ post.Post_title }}</h2> </div> </div> {% endfor %} </div> -
Pyodbc - Calling Store procedure from Django application
I have an MsSQL strore procedure which is getting executed by the command : EXEC proc_CreateProblemTicket @CurrentDate='2020-03-08'. Now I have a python django application where I need to call the store proc and passing the dynamic date. In the above example, the date is hard coded but I would like this is to dynamic. Everyday when the store proc gets executed, it should have current day. Please suggest how to do this. -
Login with oAuth2 in django using email or phone number
I am trying to implement login with oauth2 in django. Currently I am using TokenView for logging user in. But that uses username. I tried to override the default TokenView by writing something like this: class TokenView(OAuthLibMixin, View): server_class = oauth2_settings.OAUTH2_SERVER_CLASS validator_class = oauth2_settings.OAUTH2_VALIDATOR_CLASS oauthlib_backend_class = oauth2_settings.OAUTH2_BACKEND_CLASS @method_decorator(sensitive_post_parameters("password")) def create_token_response(self, request): email = request.POST.get('email', None) contact = request.POST.get('contact', None) if email or contact: username = get_user_model().objects.filter(Q(email__iexact=email)).first() | get_user_model().objects.filter(Q(contact__iexact=contact)).first() request.POST['email'] = username return super(TokenView, self).create_token_response(request) and here is my user model: class User(AbstractUser): email = models.EmailField(unique=True) contact = models.CharField(max_length=10, unique=True) username = None But I am getting an error like this AttributeError: This QueryDict instance is immutable And I get it that I cant change the value of POST request. So how can I achieve this? -
How to save and restore filters with django-filter
how can I save and restore filters with django_filters? I'm using django_filters like so: f = MyFilter(request.POST, queryset=MyModel.objects.all()) Now, I would like to be able to save my filter. That's what I tried: request.session['myfilter'] = f.form.cleaned_data I use the pickled session backend so I do not expect any trouble from there. If I try to rebuild the filter afterwards it doesn't work: f = MyFilter(request.session['myfilter'], queryset=MyModel.objects.all()) No error is displayed, but RangeFilter seem to be ignored. Of course, I could just store request.POST but this seems very ugly to me because it contains unverified data. Also, storing the queryset (f.qs) doesn't work for me because I need to be able to show the form again for editing. How to do it right? Thank you very much! -
HomeView is missing a QuerySet. Define HomeView.model, HomeView.queryset, or override HomeView.get_queryset()
i have got this error and i'm following this [tutorial][1] this is urls.py from django.urls import path from .views import HomeView urlpatterns = [ path('home/', HomeView.as_view(), name ='blog-home') ] this is my views.py from django.shortcuts import render from django.views.generic import ListView from .models import Entry class HomeView(ListView): models = Entry template_name = 'entries/index.html' -
How to upload a pre populated DataBase on Heroku?
I am making a django app and it and I am using selenium for automatically scraping the data from a site and populating my database with it. But I can't seem to find a way to run selenium on heroku. So I thought if there was any possible way by which I can populate the database on my local machine and then upload it to Heroku. -
django boto3: NoCredentialsError -- Ubale to locate credentials
I am running django website which is served by IIS on an amazon ec2 instance(windows 10) and I'm using boto3 module to send an email. I installed awscli and ran aws configure and set up my aws access keys My email sending code looks like this: import boto3 from botocore.exceptions import ClientError from django.shortcuts import redirect, render from django.http import HttpResponseRedirect def sendEmail(request): if request.method == 'POST': SENDER = "Sender Name <xxx>" RECIPIENT = "xxx" AWS_REGION = "eu-west-1" # The subject line for the email. SUBJECT = "Amazon SES Test (SDK for Python)" # The email body for recipients with non-HTML email clients. BODY_TEXT = ("Amazon SES Test (Python)\r\n" "This email was sent with Amazon SES using the " "AWS SDK for Python (Boto)." ) # The HTML body of the email. BODY_HTML = """<html> <head></head> <body> <h1>Amazon SES Test (SDK for Python)</h1> <p>This email was sent with <a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the <a href='https://aws.amazon.com/sdk-for-python/'> AWS SDK for Python (Boto)</a>.</p> </body> </html> """ # The character encoding for the email. CHARSET = "UTF-8" # Create a new SES resource and specify a region. client = boto3.client('ses', region_name=AWS_REGION) try: # Provide the contents of the email. response = client.send_email( Destination={ 'ToAddresses': … -
how to handle the Post request with many to many relation in django
I have 3 models and i want to save them they have a relation between them you are welcome to change anything and i have another issue that i'm using js function clone to add as much item as I want in the template form class Item (models.Model): name = models.CharField(("Item"), max_length=50) description = models.TextField(("Description"),blank=True, null=True) category_id = models.ForeignKey(ItemCategory, on_delete=models.CASCADE,blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class RFQ (models.Model): title = models.CharField(("Title"), max_length=100) # qty = models.CharField(("Quantity"), max_length=50) project = models.ForeignKey(Project, on_delete=models.CASCADE) item = models.ManyToManyField(Item, through='RFQItem') note = models.TextField(("Note"),blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class RFQItem (models.Model): RFQ = models.ForeignKey(RFQ, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) price =models.FloatField(("Price"), blank=True) qty = models.FloatField(("Quatity"), blank=True) note I'm using HTML and bootstrap in the template, not Django form how could I handle that in the view and save it I try something like this but it gives me an error and could not save this this is my view code def create_RFQ(request, project_id): context = {} print('aaaaaaaaaaa') if request.method == 'POST': print(request.POST) print(project_id) if not request.user.is_authenticated: return redirect("login") items = Item.objects.all() # context = {} if request.method == 'POST': print('*-*-*-*-') form1 = RFQCreate(request.POST) … -
Django, How can i count how much student every group?
i can not filter my models ,for example i need show in result, please help, thank you date group 110 students 23 date group 111 students 9 models class Group(models.Model): title = models.CharField(max_length=200, default=0) date_pub = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) def __str__(self): return self.title def datepublished(self): return self.date_pub.strftime('%d.%m.%Y') class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE,default=0) rating = models.CharField(default='5', max_length=200) date_pub = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) def __str__(self): return self.user.username views def groups(request): groups = Group.objects.all() context = { 'groups': groups } return render(request, 'panel/panel_groups.html', context) html {% for i in groups %} <tr> <td>{{ i.datepublished }}</td> <td>{{ i.title }}</td> <td>count</td> <td> <a href="{% url 'groups_detail' i.id %}" class="btn btn-secondary"> <i class="fas fa-angle-double-right"></i> Details </a> </td> </tr> {% endfor %}