Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to add a middleware which will return 200 when request method is OPTIONS
I have a requirement for testing purpose, whenever the request.method == "OPTIONS" then it should return status = 200. How can a write a middleware for this in Django -
"User object has no attribute 'encode'" when i register user
I am building a BlogApp and Today i tried to signup and then this error is keep showing 'User' object has no attribute 'encode' AND Then i tried to register in all my previous versions then this error is showing them all. BUT it was working before few days. Then i restarted my pc but still same error. When i try to save from python manage.py createsuperuser then it is also showing that error in terminal views.py def signup_view(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=200) password1 = forms.CharField(widget=forms.PasswordInput()) username = forms.CharField(help_text=False) class Meta: model = User fields = ( 'email', 'username', ) models.py @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() full traceback Traceback (most recent call last): File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\app\users\views.py", line 10, in signup_view user = form.save() File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\forms.py", line 131, in save user.save() File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save super().save(*args, **kwargs) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", … -
How to skip some rows that have errors in django-excel
I'm usign django-excel library in my Django project, and I want to skip some rows before save it to the database using the save_to_database() method. I have something like the following: file = form.cleaned_data['file'] file.save_to_database( model=MyModel, mapdict = fields, initializer=self.choice_func, ) All is working ok but I want to validate the data before call save_to_database function. The idea to do it is to add the rows that are not valid in an array and return it to notify the user that those fields not were saved. -
NOT NULL constraint failed: blogs_comment.blog_id
I'm a beginner at django please help I've been trying to solve it for 2 hours, Thank you so much! <I got this django error IntegrityError at /blog/431cdef3-d9e7-4abd-bf53-eaa7b188d0fd> `python #Views from django.shortcuts import render from .models import Blog from .forms import CommentForm def home(request): template = 'blogs/home.html' blogs = Blog.objects.all() context = {'blogs':blogs} return render(request, template, context) def blog(request, pk): template = 'blogs/blog.html' blog = Blog.objects.get(pk=pk) context = {'blog':blog} if request.method == 'POST': form = CommentForm(request.POST) form.save() else: form = CommentForm() context['form'] = form return render(request, template, context) #Forms from django.forms import ModelForm from .models import Comment class CommentForm(ModelForm): class Meta: model = Comment fields = ['description'] #Models from django.db import models import uuid class Blog(models.Model): header = models.CharField(max_length=200) posts = models.TextField(null=True) footer = models.TextField(null=True, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.header class Comment(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comments') description = models.TextField(blank=True, null=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.description ` -
Is there a way to make a circle around Long & Lat, say a 5 miles?
I am looking to make a radius of 5 miles using known longitude & latitude. how do we do that math in python? Thank you for your wisdom in advance. -
django and axios: why OPTIONS is requested when POST (restapi) is requested
I am using axios for doing a POST request in my reactjs page. const url = "test/"; const data = { email: "test@test.com", password: "test", }; const headers = { headers: { Accept: "application/json", "Content-Type": "application/json", }, }; axios.post(url, data, headers) .then((res) => { console.log(res); }) .catch((err) => { console.log(err); }) In my Django view(which corresponds to the url) I have intentionally put a wrong python statement. i.e def test(request): a+=1 And when run the axios code i get and also In my Django console i see: Traceback (most recent call last): ......... ........../views.py", line 139, in test a+=1 NameError: name 'a' is not defined But generally if I am not using rest api, Django shows the traceback html when anything wrong happens in the browser itself. Even with ajax i can see the response in the developertools. But with axios its not showing Can someone help how to achieve this. I want to capture the traceback also in the script -
How to solve 'This field is required' for django forms
I created a blog like app. Whenever I update an entry and press the submit button, I want it to take me to view page for that blog entry. However it just redirects me to the update page. When I check form.errors it says that 'This field is required' for all of the fields. But all of the fields are filled with data. views.py from django.shortcuts import render,redirect from .models import CR,GC from .forms import CrForm,GcForm # Create your views here. def Home(request): return render(request,'base.html') def crlistview(request): crs = CR.objects.all() context = {'crs':crs} return render(request,'cr_list.html',context) def CreateCr(request): form = CrForm() if request.method == 'POST': form = CrForm(request.POST) if form.is_valid(): form.save() return redirect('crlist') context = {'form':form} return render(request,'cr_form.html',context) def UpdateCr(request,pk): cr = CR.objects.get(id=pk) form = CrForm(instance=cr) context = {'form':form,} if request.method == 'POST': form = CrForm(request.POST,instance=cr) if form.is_valid(): form.save() return redirect('crlist') return render(request,'cr_form.html',context) def gclistview(request): gcs = GC.objects.all() context = {'gcs':gcs} return render(request,'gc_list.html',context) def gcview(request,pk): gc = GC.objects.get(id=pk) context = {'gc':gc} return render(request,'gc_view.html',context) def UpdateGc(request,pk): gc = GC.objects.get(id=pk) form = GcForm(instance=gc) context = {'form':form} if request.method == 'POST': form = GcForm(request.POST,instance=gc) if form.is_valid(): form.save() return redirect('gcview') return render(request,'gc_update.html',context) forms.py from django.forms import ModelForm from django import forms from .models import CR, … -
Remove underline from href attribute that reference a Django template
At the top of one of my website pages, I have some text representing the name of my company. When the user clicks the text (a link in this case), they are redirected to the index route via the Django template. Currently, the text is decorating. It's always the traditional blue color of a hyperlink and it's underlined when the user hovers over it. I'm trying to turn off this text decoration. Here is my attempt (which doesn't work): layout.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="{% static 'my_app/styles.css' %}" rel="stylesheet"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Pacifico"> </head> <body> <div id="logo"> <a href="{% url 'index' %}">ABC Company</a> </div> </body> CSS #logo { font-family: 'Pacifico', serif; text-align: center; font-size: 60px; font: 400 100px/1.5; color: #2b2b2b; text-decoration: none; } #logo:hover { text-decoration: none; } If I remove the href, the text goes back to the color specified in the #logo id in the CSS. Any ideas why the text-decoration isn't being turned off? Thanks in advance! -
How to get in Django Month / Year Archive as a list in first page?
looking to make a list by month in home page for iterate in first page like this: Aug 2021 July 2021 Jun 2021 and every month has no post, don't show in this list. this my code: #blog/models.py class Post(models.Model): title = models.CharField(max_length=255) content = RichTextField() author = models.ForeignKey(User,on_delete=models.CASCADE,) created_at = models.DateTimeField(auto_now_add=True) published_at = models.DateTimeField(null=True, blank=True, editable=False) #blog/views.py def month_archive(request, year, month): a_list = Post.objects.filter(created_at__year=year).filter(created_at__month=month) context = { 'year' : year, 'month': month, 'month_archive' : a_list, } return render(request, 'blog/month_archive.html', context) def home(request): posts = Post.objects.all() paginator = Paginator(posts, 5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'posts': posts, 'page_obj': page_obj, } return render(request, 'blog/home.html', context) and i want to show it in home.html like: <li><a href="/blog/archive/2021/08">Aug 2021</a></li> <li><a href="/blog/archive/2021/07">Jul 2021</a></li> ... -
Django + Disable Caching for extended viewset
How to disable Django Cacheing for one of the viewset in below scenario ? I want to disable caching for viewset with name SecondViewSet, I am using @method_decorator(never_cache, name="list") on SecondViewSet it is not working, kindly advise Abstract Viewset class AbstractDataViewSet(ListAPIView): http_method_names = ['get', 'options'] permission_classes = [IsAuthorizedUser] @method_decorator(cache_page(settings.VIEWSET_CACHE_TIMEOUT)) def list(self, request, *args, **kwargs): return Response(data={"message":"appdata"} First Viewset class FirstViewSet(AbstractDataViewSet): group_permissions = { 'GET': ( roles.ACCOUNTING, ) } Second Viewset class SecondViewSet(AbstractDataViewSet): group_permissions = { 'GET': ( roles.ACCOUNTING, ) } Third Viewset class ThirdViewSet(AbstractDataViewSet): group_permissions = { 'GET': ( roles.ACCOUNTING, ) } -
vscode django debugging error: Couldn't import Django
I tried to debug a django project using vscode. But the next one came. ImportError Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? File "/Users/cubest_june/hj-django/english/manage.py", line 11, in main from django.core.management import execute_from_command_line The above exception was the direct cause of the following exception: File "/Users/cubest_june/hj-django/english/manage.py", line 13, in main raise ImportError( File "/Users/cubest_june/hj-django/english/manage.py", line 22, in <module> main() Even when I just ran python manage.py runserver, it ran without any problems, and both Django and Python are installed. (django-envs) ➜ english git:(main) ✗ django-admin --version 3.2.5 (django-envs) ➜ english git:(main) ✗ python --version Python 3.9.0 What is the cause of this problem and how to fix it? This is my first time doing something like this, so I don't know what kind of information I need. Let me know and I'll edit it. -
What is wrong--Mobile Compatibility not Working
I have been working on a website and at the moment, the header works and is responsive in desktop but when I get to mobile, the bootstrap doesn't show and it doesn't interact with mobile this is my code I have so far if anyone could tell me what is wrong that would be super helpful. <div class="continer-fluid"> <nav class="navbar navbar-inverse bg-inverse navbar-fixed-top"> <div class="navbar navbar-expand-lg "> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="container"> <a href="/" class="navbar-brand"> <img src="{% static "app/content/collectore-luxury-logo11.png" %}" width="30" height="30" class="d-inline-block align-top" alt=""> Website </a> <div class="collapse navbar-collapse " id="#navbarSupportedContent"> <ul class="nav navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item"><a href="{% url 'home' %}">Home</a></li> <li class="nav-item"><a href="{% url 'about' %}">About</a></li> <li class="nav-item"><a href="Medium Blog">Blog</a></li> <li class="nav-item"><a href="{% url 'New Thing' %}">New Thing</a></li> </ul> -
How to render all data related to object id in views.py
I am trying to create a webapp for a restaurant to display the different menus available, Breakfast, Lunch, evening etc. I have created models for Menu, Menu Category and Menu Items. I have a menu.html page that displays the available menus to view image of menu list on site . What I would like to happen when a user clicks the menu they wish to view is a menu_detail page to load and populated with required categories and items for that particular menu. Currently when clicked it will load the correct menu based on id but then only load a single category with the same id not all categories related to that menu and wont render any items models.py from django.db import models """ A Menu represents a collection of categories of food items. For example, a restaurant may have a Lunch menu, and a Dinner menu. """ class Menu(models.Model): name = models.CharField(max_length=246, unique=True,) slug = models.SlugField(max_length=24, unique=True, help_text='The slug is the URL friendly version of the menu name, so that this can be accessed at a URL like mysite.com/menus/dinner/.') additional_text = models.CharField(max_length=128, null=True, blank=True, help_text='Any additional text that the menu might need, i.e. Served between 11:00am and 4:00pm.') order … -
Django For Backend, Frontend Or Both
Please can Django be used to create a full functioning web application in Backend, Frontend or both and if so, can anyone suggest sites to learn on, a tutorial or complete web application course on Django or smth relating to how to code using Django. Thank You -
Image update issue in drf using put method
I am using Django rest framework, I have a issue regarding update my html data with image field using put method. Everthing is fine in response using postman but when i use ajax then it gives me following error in console. PLease help to resolve this issue. I want to update my data with image using put method only but above error interrupt my work. Please help me to resolve my issue I want to update my data with image using put method only but above error interrupt my work. Please help me to resolve my issue My views,py file: @api_view(['PUT']) # @csrf_exempt @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def update_blog(request, id): try: blog = Blog.objects.get(id=id) except Blog.DoesNotExist: return Response(status=404) if blog.user_id != request.user.id: return Response({'response':'You do not have permission to update that'}) if request.method == 'PUT': serializer = AddBlogSerializer(blog, context={'request': request}, data=request.data) if serializer.is_valid(): serializer.save() data = {'result':'success', 'message':'Blog post updated successfully'} return Response(data=data, status=200) if not serializer.is_valid(): data = { 'result': 'error', 'message':serializer.errors} return Response(data=data) My response data is fine in views.py file My bootstrap html modal <!-- Modal --> <div class="modal fade" id="exampleModal1" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Update Blog</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" … -
Using proxy model as a signal sender
I have a proxy model. class ProxyModel(ParentModel): objects = ProxyModelManager() class Meta: proxy = True I'm trying to define my proxy model as a sender. @receiver(post_save, sender=core_models.ProxyModel) def test_receiver(sender, instance, **kwargs): print("test receiver") But the function is not called after the model is saved. Is it possible to define proxy model as sender? If so how can I do ? Thanks. -
my Django forms not working and also not submitting
I am not understanding why my forms not submitting. It seems to me everything correct in my code. Where I am doing mistake: views.py: projectfroms = CustomerProjectFroms(request.POST or None) if request.method == "POST": if projectfroms.is_valid(): projectfroms.instance.user = request.user messages.add_message(request, messages.INFO,'You project submitted sucessfully') projectfroms.save() return redirect('members:user-profile-private') else: messages.add_message(request, messages.INFO,"You project didn't submitted sucessfully") else: projectfroms = CustomerProjectFroms() I am getting this message "You project didn't submitted sucessfully" which confirm me my forms not submitting and I also rechecked from admin panel. models.py: class CustomerProject(models.Model): user = models.ForeignKey(UserManagement,on_delete=models.CASCADE) project_title = models.CharField(max_length=2000,blank=True,null=True) project_description = models.TextField(blank=True,null=True) froms.py class CustomerProjectFroms(forms.ModelForm): class Meta: model = CustomerProject fields = ['project_title','project_description'] -
Why do some images have the little magnifying glass?
I added an image to a "rich text" block of my website, but it displays with a little magnifying glass in the corner that allows you to see the image full size. I don't want this. I've looked at other images on the same site that don't have the little magnifying glass, to try to figure out what I did differently, but I can't figure it out. Please help. -
This is an hard one: allow users to send email through their own gmail without in a scalable way on django
This is an hard one I am making a django application to help people assemble construction workers teams. The app works as follow (more or less): A user sign up and upload all it's contacts. Each contact has an emails, a job title and a preference (how much the user like to work with this person). The user create a job element and select all the positions he needs to fill for the job (I need 2 carpenters, 1 cement guy...). The app start sending out email to the users' contact that have the right title starting by the one with the highest preference to check if they are available and interested for the job. If the person it's interested, they click on an link in the email and the position is marked as filled. If the person it's not interested, they click on another link and the app reach out to the next contact in line. I set up the whole app but I am having some troubles with how to send emails. I initially though about using Gmail API but I am now realizing that doing requires that every user goes into Google Api Console, download their credentials … -
How to create multiple instances of a model with factoryboy in django?
How do I create multiple instances of this Resource? When I try to do it, I get the same instance created. I do tend to end up with it creating multiple users, but only one Resource. Here is the factory declaration class ResourceFactory(DjangoModelFactory): class Meta: model = Resource client = factory.SubFactory( ClientFactory, ) user = factory.SubFactory( UserFactory, ) start_date = Faker("date_time") end_date = None department = Faker("sentence", nb_words=2) title = Faker("sentence", nb_words=4) custom_data_field = {"fake": "data"} This is roughly how I have been trying to do things. I want all resources associated with the same client. At this point, I got the client from the database, because I was getting random errors, and that seemed to fix those errors, at least. client = ClientFactory() db_client = Client.objects.get(id=client.id) resources = [ResourceFactory(client=db_client) for i in range(5)] if I run len(Resource.objects.all()) at this point, it comes back as 1. How do I create 5 separate resources in the database, all associated with the same client? -
Bootstrap / Django: recommended way to render two cards side-by-side (with responsiveness)
I have the following index.html page that leverages Django templates: {% extends "layout.html" %} {% block body %} {% for entry in entries %} <div class="card h-100 mb-3" style="max-width: 540px;"> <a href="{% url 'entry' entry.id %}"> <img class="card-img-top" src="{{ entry.image.url }}" alt="{{ entry.title }}"> </a> <div class="card-body"> <h5 class="card-title">{{ entry.title }}</h5> <p class="card-text">{{ entry.description }}</p> {% endif %} </div> </div> {% empty %} No content found. {% endfor %} {% endblock %} Currently, the Bootstrap cards render in a single column (one on top of the other), and they're left-justified. What is the best way to render cards such that there are two cards side-by-side (and responsive to become a single column if the screen becomes narrow)? Thanks in advance! -
Why is the checkbox not being saved as checked? (Python, Django, HTML)
I was following this tutorial by Tech with Tim, but after adding the code from the video, my checkboxes wont work. My code: views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import Item, ToDoList from .forms import CreateNewList # Create your views here. def index(response): return HttpResponse("<h1>Hello, world!</h1>") def item_by_id(id): item = Item.objects.get(pk=id) return HttpResponse(f"Item: {item.title}, published on {item.datetime_found}") def home(response): return render(response, "myapp/home.html", {}) def base(response): return render(response, "myapp/base.html", {}) def itemlist(response, list_id): ls = ToDoList.objects.get(id=list_id) if response.method == "POST": print(response.POST) # SAVING CHECK-BUTTONS if response.POST.get("save"): for item in ls.listitem_set.all(): if response.POST.get("c" + str(item.id)) == "clicked": item.complete = True else: item.complete = False item.save() # ADDING ITEM TO LIST elif response.POST.get("newListItem"): txt = response.POST.get("new") if len(txt) > 2: ls.listitem_set.create(text=txt, complete=False) else: print("Invalid") return render(response, "myapp/itemlist.html", {"ls": ls}) def create(response): if response.method == "POST": form = CreateNewList(response.POST) # Takes POST and uses data for form if form.is_valid(): # is_valid() checks class-fields for valid input n = form.cleaned_data["name"] # Clean and un-enc data, specify field "name" t = ToDoList(name=n) # Use data to create new ToDoList t.save() return HttpResponseRedirect("itemlist/%i" % t.id) # Redirect to page that shows the list else: form = CreateNewList() return render(response, "myapp/create.html", {"form": … -
Python Django - PostgresSQL Database Awith Amazon RDS Shuts Down After pgAdmin app is closed
I am working on a Django project right now and want to use Postgres for my database. I am somewhat confused on how sending data to the database (hosted on Amazon RDS) works. I have it currently set for inbound rules as my IP, as most articles say to do. When I eventually move to production, I'd imagine these inbound rules don't work. What rules should I use so that users can access the data in the database? -
AttributeError: 'IsInvited' object has no attribute 'request'
I have a modelviewset like this: class MeetingViewSet(viewsets.ModelViewSet): queryset = Meeting.objects.all() serializer_class = MeetingSerializer permission_classes =[IsAuthenticated & IsInvited | IsOwner] and permissions: class IsInvited(BasePermission): message = 'you must have been invited to see this meeting' def has_object_permission(self, object, request, view): if self.request.method == 'GET' and object.is_invited(self.request.user): return True return False class IsOwner(BasePermission): def has_permission(self, request, view): return request.user and request.user.is_authenticated def has_object_permission(self, object, request, view): if self.request.user == object.host: return True return False but i got this error : Internal Server Error: /api/meetings/1/ Traceback (most recent call last): File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/mixins.py", line 54, in retrieve instance = self.get_object() File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/generics.py", line 99, in get_object self.check_object_permissions(self.request, obj) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 345, in check_object_permissions if not permission.has_object_permission(request, self, obj): File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/permissions.py", line 81, in has_object_permission self.op1.has_object_permission(request, view, obj) or … -
Can i implement django rest api with just jquery and ajax in production?
I am quite new to django rest framework. Is it appropriate if I implement Django rest framework without react front-end or anything like that but just with simple jquery UI ajax. And can I use it in production. It would be really nice to have your expert opinion.