Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
render the sent and received messages when a message is sent
I'm trying to build a chat app using only React js and Django. When I type a message in the input and hit send, it grabs the input and sends it to the API, the API returns the message and I render it using useEffect, next if I get a reply I want to render it as well, the problems are:- 1)when I hit send I'm getting an internal server error status 500, but the number I'm sending the message to is getting the message, which means the message is being sent. 2)when the useEffect runs after sending the message, it continuously starts running & doesn't stop. 3) I'm only getting the delivered message, not the received ones from the api. Please please help me solve these problems. The Chat component: import React, { useEffect, useState } from 'react' import ArchiveOutlinedIcon from '@material-ui/icons/ArchiveOutlined'; import './chat.css' import { IconButton } from '@material-ui/core'; import AddIcon from '@material-ui/icons/Add'; //ICONS import SendIcon from '@material-ui/icons/Send'; import NoteIcon from '@material-ui/icons/Note'; import { Link, useParams } from 'react-router-dom'; import axios from 'axios'; interface ParamTypes { userId: string } const ChatBox = () => { const { userId } = useParams<ParamTypes>() const [messages, setMessages] = useState<any[]>([]) const [formInput, … -
How to case insensitive username and email for a Django Project
I have the following authentication for users in Django: class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) Users can log in using their Username or email but if the email or user name has a case sensitive letter it shows as an error: Please enter the correct username and password. Note that both fields may be case-sensitive. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] My question: How can authenticate users with case insensitive username or email: -
django elasticsearch-dsl pagination help me.... 😥
I am a newbie in Elasticsearch.. How can i use django pagination on elasticsearch dsl. My code: views.py from django.http import HttpResponse from django.http import Http404 from django.template import loader from .models import acct_file from .models import user_file from elasticsearch import Elasticsearch from elasticsearch_dsl import Search, Q, FacetedSearch, TermsFacet, DateHistogramFacet from elasticsearch_dsl.query import MultiMatch, Match from django.shortcuts import render, redirect, get_object_or_404 from django.core.paginator import Paginator, Page, EmptyPage, PageNotAnInteger from django.utils.functional import LazyObject es = Elasticsearch('https://74db6d511634413eb######8db11.us-central1.gcp.cloud.es.io:###$') class DSEPaginator(Paginator): def __init__(self, *args, **kwargs): super(DSEPaginator, self).__init__(*args, **kwargs) self._count = self.object_list.hits.total def page(self, number): # this is overridden to prevent any slicing of the object_list - Elasticsearch has # returned the sliced data already. number = self.validate_number(number) return Page(self.object_list, number, self) def tranls(request): q = request.GET.get('q', None) page = int(request.GET.get('page', '1')) start = (page-1) * 10 end = start + 10 es = Elasticsearch(["https://74db6d511634413eb######8db11.us-central1.gcp.cloud.es.io:###$"], http_auth=('elastic', 'elastic'), scheme="http" ) s = Search(using=es, index="django")[0:12].sort({"t_day": {"order": "desc"}}) response = s.execute() paginator = DSEPaginator(response, 5) try: response = paginator.page(page) for a in response: print(a) except Exception as e: print(e) context = { "django": response, } return render(request, 'polls/tranls.html', context) tranls.html <div class="col-sm border m-1 bg-white"> <div> <table class="table table-hover" style="font-size: 12px;"> <thead> <tr> <th scope="col">t_id</td> <th scope="col">t_userid</td> <th … -
Heroku: gunicorn and waitress-serve commands not working
I'm building a website which I want to deploy to Heroku. I used an empty django project, configured the static root and tried to deploy it. When I deploy it, This is what Heroku shows me this: Image Here is what the console showed: image I found out that gunicorn was not a function even though I had installed it, as the Heroku bash said that the command was not found. I also tried using waitress, but the issue persisted. I also tried using python. I use a Windows 10 PC and I used the Heroku CLI to deploy the Django application. I have gunicorn and waitress in my requirements.txt and I have tried installing and running gunicorn in the heroku console using pip install gunicorn && gunicorn mysite.wsgi. I want to know how I can get the server running. Thanks in advance! -
How to change inlines when creating a object
currently I have the following code: @admin.register(Experience) class ExperienceAdmin(admin.ModelAdmin): list_display = ('type', 'start_date', 'end_date') inlines = [AcademicInline, ProfessionalInline] def get_inline_instances(self, request, obj=None): pass I would like to register a experience for an user, but the user can pick just one, Academic or Professional. I would like to use the type field of Experience to do it, when the user pick type Academic, I'll show AcademicInline, when the user pick Professional, I'll show ProfessionalInline. this registration needs to be done using the django admin module. I've tried to use get_inline_instances but all my attempts failed. Please, let me know if you need more information or a more detailed explanation. -
Django-Sorting-Bootstrap Heroku push failing
I'm deploying a django project with django-sorting-bootstrap on heroku and I'm having some trouble. Here's my error Could not find a version that satisfies the requirement django-sorting-bootstrap==2.6.2 (from -r (my folder)/requirements.txt (line 65)) (from versions: 1.0.0, 1.0.1, 1.0.2, 1.1, 1.1.1) Any idea why the versions only go up to 1.1.1 when the latest release is 2.62? -
How to customize errors with django-graphql-auth?
I'm working on a project with Django and Graphene, with the library of django_graphql_auth to handle authentication, and i was asked to customize the error message that we receive when we fail a login. I've readed the docs over how to do this, and it only mentions a setting called CUSTOM_ERROR_TYPE( https://django-graphql-auth.readthedocs.io/en/latest/settings/#custom_error_type ), but i think i'm not understanding how to use it, or maybe it doesn't work the way i think it does. On my files i've: custom_errors.py import graphene class CustomErrorType(graphene.Scalar): @staticmethod def serialize(errors): return {"my_custom_error_format"} settings.py from .custom_errors import CustomErrorType GRAPHQL_AUTH = { 'CUSTOM_ERROR_TYPE': CustomErrorType, } user.py class AuthRelayMutation(graphene.ObjectType): password_set = PasswordSet.Field() password_change = PasswordChange.Field() # # django-graphql-jwt inheritances token_auth = ObtainJSONWebToken.Field() verify_token = relay.VerifyToken.Field() refresh_token = relay.RefreshToken.Field() revoke_token = relay.RevokeToken.Field() unlock_user = UsuarioUnlock.Field() class Mutation(AuthRelayMutation, graphene.ObjectType): user_create = UserCreate.Field() user_update = UserUpdate.Field() user_delete = UserDelete.Field() schema = graphene.Schema(query=Query, mutation=Mutation) Yet, when i test the login, i receive the message: "Please, enter valid credentials." What should i do to change that message? -
Iframe not adding sessionid cookie
I'm trying to showcase a CSRF attack against a dummy app using Django for a workshop. I just created a basic Django 3.1.6 app with authentication, removed all CSRF protections from it and created a page that I simply open with the broser with something like: <iframe style="display:none" name="csrf-frame"></iframe> <form method='POST' action='http://127.0.0.1:8000/edit/' target="csrf-frame" id="csrf-form"> <input type="hidden" name="email" value="NEWEMAIL" /> <input type='submit' value='submit'> </form> <script>document.getElementById("csrf-form").submit()</script> Problem is, browsers have become so (rightfully) paranoid with sending cookies that this POST request doesn't append the sessionid cookie. If tried setting the cookie same site to be None by adding SESSION_COOKIE_SAMESITE = 'None' but to no success even though I see the SameSite value change from lax to empty. I reading around I understand this would work if I was under HTTPS and setting SESSION_COOKIE_SECURE = True. Is this the case? Any suggestion on how to make it work using my dummy app and attack page in localhost? -
TypeError at /admin/auth/user/add/ save() got an unexpected keyword argument 'force_insert'
I use signals.py to create a profile object when a user object is created. This used to work before but it does not work any more whether I use my code or I use admin panel to create a user. Code for creating a Profile object is as follows: @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() If I comment this signals.py the error (when I add a User) goes away, bypassing creation of a Profile object when a User is created. Profile clasa has this code: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pictures') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() image = Image.open(self.image.path) if image.height>300 or image.width>300: size = (300, 300) image.thumbnail(size) image.save(self.image.path) I use Windows 7 with Python 3.7.9 using db.sqlite3 . HELP!! -
django get_absolute_url redirecting issue
I have an object from which I want to have two get_absolute_urls, since I have two categories(rent,sale). However, if I set get_absolute_url 'rent' last, the items from sale are redirecting to 'rents' url ex: rents/1. How can I make this to work? model: class Listing(models.Model): agent = models.ForeignKey(Agent, on_delete = models.DO_NOTHING) title = models.CharField(max_length=120) address = models.CharField(max_length = 120) area = models.CharField(max_length=120) description = models.TextField(blank = True) price = models.IntegerField() bedrooms = models.DecimalField(max_digits=2, decimal_places=1) bathrooms = models.DecimalField(max_digits=2, decimal_places=1, blank = True, null = True) garage = models.IntegerField(default = 0) sqft = models.IntegerField() categories= (('sale', 'sale'),('rent','rent')) category= models.CharField(max_length = 10, choices= categories, null = True) lot_size = models.DecimalField(max_digits=5, decimal_places=1) photo_main = models.ImageField(upload_to = 'photos/%Y/%m/%d/') photo_1 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank = True, null = True) photo_2 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank = True, null = True) photo_3 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank = True, null = True) photo_4 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank = True, null = True) is_published = models.BooleanField(default = True) is_featured = models.BooleanField(default = True) list_date = models.DateTimeField(default=datetime.now, blank = True) def __str__(self): return self.title def get_absolute_url(self): return reverse('sale', args=[str(self.id)]) def get_absolute_url(self): return reverse('rent', args=[str(self.id)]) urls path('rents/',rents, name = 'rents'), path('rents/<int:pk>',RentView.as_view(), name = 'rent'), path('sales/',sales, name = 'sales'), … -
Django Rest Framework post request with nested serializer as a list
I'm trying to create an object with a serializer from a post request but I'm getting an error while trying to pass a list of objects to a nested serializer. While passing the ('id', 'name', 'description') data in a JSON format works just fine the list of bars is not getting parsed properly and return the following error : {'bars' : [ErrorDetail(string='This field is required.', code='required')]}} This is the Serializer : class FooSerializer(serializers.ModelSerializer): bars = BarsSerializer(many=True) class Meta: model = Foo fields = ('id', 'author' 'name', 'description', 'bars') def create(self, validated_data): validated_data['author'] = self.context['request'].user # Foo object manager is tested and works return Foo.objects.create(**validated_data) This is my request payload : { 'name': "A Foo", 'description': "A happy foo running in the woods of Central Park", 'bars': [ {name : 'a'}, {name : 'b'}, {name : 'c'}, ] } note that Foo and Bar are both simplified model of my real models to reduce the information amount of the given problem -
Django forms - object has no attribute error when trying to reference one of the form fields
Well this is really confusing to me, whenever I execute the view I get an error at x = form.file_name form has no attribute file_name. However, when I comment out the line x = form.file_name the html {{form.file_name}} does not return an error and a file browser is outputted to the page. How come form.file_name returns an error when executed in views.py but not in upload.html? upload.html {{form.file_name}} views.py def upload(request): form = CsvForm(request.POST or None, request.FILES or None) x = form.file_name return render(request, 'upload/upload.html', {'form' : form}) forms.py class CsvForm(forms.ModelForm): class Meta: model = Csv fields = ('file_name', 'public') models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Csv(models.Model): file_name = models.FileField(upload_to='csvs', max_length = 100) public = models.BooleanField(default = False) user = models.ForeignKey(User, on_delete = models.CASCADE, null = True) def __str__(self): return "File id: {}".format(self.id) -
Django: rest api: Not recieving the complete json string when its very big
I am sending a very long json string using @api_view(['GET']) def sendlargedata(request): .... return HttpResponse(json.dumps(all_graphs_data,default=str),status=200,content_type="application/json") When i check the data in the firefox response it says SyntaxError: JSON.parse: unterminated string at line 1 column 1048577 of the JSON data so how to oversome any size or length restrictions and send the data and recieve -
Django - How can I return error messages if user already exists during registration?
Using Django REST, and I'm trying to implement simple warnings that warn users if an email and/or username is currently in use, during registration flow. I've tried implementing it using UniqueValidator, but there does not to be much information about it. Also wondering if I should just ditch that and use something else. Here is my serializer: from rest_framework import serializers from rest_framework.validators import UniqueValidator from users.models import User class CustomUserSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator( queryset=User.objects.all(), message="This email is already in use")]) username = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all(), message="This username is already in use")]) password = serializers.CharField(min_length=8, write_only=True) first_name = serializers.CharField(max_length=30) last_name = serializers.CharField(max_length=30) subscribed = serializers.BooleanField(default=False) class Meta: model = User fields = ('email', 'username', 'password','first_name','last_name','subscribed') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance view.py: class CustomUserCreate(APIView): permission_classes = [AllowAny] def post(self, request, format='json'): serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: json = serializer.data return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Please let me know how I can make this validation process as effective as possible. -
Django SafeDelete
I'm using the following library in my Django project https://pypi.org/project/django-safedelete/. All my models are setup for "cascading soft delete" and I'm having some trouble. One example of the problem I'm having: In my application, I have a "vendor" model that has a foreign key to the main "user" model. These are also both set to cascading soft delete. class VendorProfile(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE creation_time = models.DateTimeField(auto_now_add=True, editable=False) modified_time = models.DateTimeField(auto_now=True) user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='vendor_profile') The problem is this - let's say I go into the Django admin and delete a vendor model. It does NOT delete the associated user model, as it shouldn't, but then, anytime past that in code that I make calls such as: hasattr(user, "vendor_profile") will return True even though the vendor profile was deleted. The vendor profile objects are not visible in the admin and I'm quite confused why there's this discrepancy. Should I use a different library/make my own abstract model? Thank you in advance! -
Bootstrap Code not Displaying Correctly in Webpage
So I am practicing working with Python and Django using Corey Schafer's YouTube series, where we are just making a blog page. https://www.youtube.com/watch?v=qDwdMDQ8oX4&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&index=3&ab_channel=CoreySchafer Everything was going well, but when I added the bootstrap code I noticed that my web page wasn't showing up how I expected. In the tutorial his page originally showed up exactly how mine did, but he was able to kill the terminal and refresh the page to have it load correctly. When I attempted that nothing happened. I also tried to clear my browser cache as he suggested could be a potential solution, but that didn't help much either. Here is my main.css in my templates\blog\static\blog directory: body { background: #fafafa; color: #333333; margin-top: 5rem; } h1, h2, h3, h4, h5, h6 { color: #444444; } ul { margin: 0; } .bg-steel { background-color: #5f788a; } .site-header .navbar-nav .nav-link { color: #cbd5db; } .site-header .navbar-nav .nav-link:hover { color: #ffffff; } .site-header .navbar-nav .nav-link.active { font-weight: 500; } .content-section { background: #ffffff; padding: 10px 20px; border: 1px solid #dddddd; border-radius: 3px; margin-bottom: 20px; } .article-title { color: #444444; } a.article-title:hover { color: #428bca; text-decoration: none; } .article-content { white-space: pre-line; } .article-img { height: 65px; width: 65px; … -
How to count the content in databse django?
I am learning Django and my first project I am doing a To do application. My idea is that I put the content from the database(models.py) into tables in html ,but also on the side of the table I have put a number that starts from 1 and for every other task(content) that is put from customer in the web it also puts 2, 3 .... etc. The problem I have is that when I add a task number it becomes 2 for what I just added but also for the task that was before. This is a screenshot to understand it easily This is views.py: from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from .models import * from .models import __str__ # Create your views here. def home(request): count_item = todo.objects.count() all_items = todo.objects.all().order_by("created") context = {'all_items': all_items, 'count_item':count_item} return render(request, 'html/home.html', context) def add_todo(request): current_date = timezone.now() new_item= todo(content = request.POST["content"]) new_item.save() return redirect('/') def delete_todo(request, todo_id): item_to_delete = todo.objects.get(id=todo_id) item_to_delete.delete() return redirect('/') This is home.html: {% extends 'html/main.html' %} {% load static %} {% block content %} <style> </style> <nav class="navbar navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#">TO DO APPLICATION</a> <form class="d-flex" … -
Django Admin does not encrypt password
I'm making a project that there will be an admin, and He/She will register the users. But when I create a user by admin interface, the password is not being encrypted. What could it be? user model from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import BaseUserManager # Create your models here. class UsuarioManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('Email é obrigatorio') email = self.normalize_email(email) user = self.model(email=email, username=email, **extra_fields) user.set_password(password) user.save(using=self._db) return def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser precisa ter is_superuser=True') if extra_fields.get('is_staff') is not True: raise ValueError('Superuser precisa ter is_staff=True') return self._create_user(email, password, **extra_fields) class Usuario(AbstractUser): USERNAME_FIELD = 'email' email = models.EmailField(('email address'), unique=True) REQUIRED_FIELDS = [] # removes email from REQUIRED_FIELDS funcionario = models.BooleanField("funcionario", null=True, blank=True) cliente = models.BooleanField("cliente", null=True, blank=True) def __str__(self): return super().first_name + " " + super().last_name objects = UsuarioManager() As I create a superuser on cmd, the password is encrypted normally. -
Django pagination not working. Object list is rendering items but not dividing into pages
I'm currently working on an e-commerce site and I'm trying to create a product list page that spans into another page after 4 items have been displayed. rendering the page doesn't produce any error but all items in the database are displayed on the same page and remains the same even after switching to another page. Here's my views.py: from django.shortcuts import render, get_object_or_404 from .models import Category, Item from django.core.paginator import Paginator def item_list(request, category_slug=None): category = None categories = Category.objects.all() items = Item.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) items = items.filter(category=category) paginator = Paginator(items, 4) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'item/list.html', {'category': category, 'categories': categories, 'page_obj': page_obj, 'items': items}) my urls.py file: from django.urls import path from . import views app_name = 'shop' urlpatterns = [ path('', views.item_list, name='item_list'), path('<slug:category_slug>/', views.item_list, name='item_list'), path('<int:id>/<slug:slug>/', views.item_detail, name='item_detail'), pagination snippet from the template <nav class="d-flex justify-content-center wow fadeIn"> <ul class="pagination pg-blue"> <!--Arrow left--> {% if page_obj.has_previous %} <a href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">Next</a> {% endif %} </ul> </nav> and the logic that displays the products <div class="row … -
Django models: How to filter by multiple values at once?
I'm working on a social network project for learning purposes and I'm trying to figure out the best way to make this query: def following(request, user_username): user = User.objects.get(username=user_username) try: following_users = user.following.all() following_posts = [] for following_user in following_users: following_posts.append(Post.objects.filter(username=following_user.username)) except: return JsonResponse({"error": "There was an error loading the following posts"}, status=400) following_posts = following_posts.order_by("-timestamp").all() return JsonResponse([post.serialize() for post in following_posts], safe=False) I'm trying to get the posts of the users that the user is following in the social media, ordered by reverse chronological order ("timestamp"). And, to do that, I tried first getting all the users that the user follows (following_users = user.following.all()) and then getting all the posts these users has one by one (in the for loop). The problem is that the order_by function only works with QuerySet, and the following_posts is a list. Not only that, I don't think that this is a good way to make this query even if it worked. Can I get all these posts at once without a for loop? Anyway, these are the models that are involved in this query: class User(AbstractUser): profile_picture = models.CharField(max_length=100, default="https://cdn.onlinewebfonts.com/svg/img_568656.png") followers = models.ManyToManyField('self', blank=True) following = models.ManyToManyField('self', blank=True) join_date = models.DateTimeField(auto_now_add=True) def serialize(self): … -
Implementing Language switcher
I'm trying to implement language switcher a web-application using django. I have written the html part and it's showing the current language that I'm using but for some reason the dropdown menu which contains the flag list is not showing this is what I've written so far: $("#language-list a").on('click', function (event) { event.preventDefault(); var target = $(event.target); var url = target.attr('href'); var language_code = target.data('language-code'); $.ajax({ type: 'POST', url: url, data: {language: language_code}, headers: {"X-CSRFToken": getCookie('csrftoken')} }).done(function (data, textStatus, jqXHR) { reload_page(); }); }); <form class="d-flex"> <ul class="navbar-nav mx-0 me-auto mb-2 mb-lg-0"> <li class="nav-item dropdown"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><img src="/static/img/flags/{{LANGUAGE_CODE}}.png">&nbsp;<span class="caret"></span></a> <ul class="dropdown-menu" role="menu" id="language-list"> {% for language in languages %} <li> <a href="" data-language-code="{{ language.code }}"> {% if language.code == LANGUAGE_CODE %}&#10003;{% else %}&nbsp;&nbsp;{% endif %} <img src="/static/img/flags/{{ language.code }}.png"> {{ language.name_local }} </a> </li> {% endfor %} </ul> </li> </ul> </form> -
How to insert data with create in Django
How to insert data with create in Django thank you Model class Cliente(models.Model): seguimento = models.PositiveIntegerField() Form class ClienteForm(forms.Form): seguimento = forms.IntegerField() def create(self, validated_data): client = Cliente.objects.create(**validated_data) view form = ClienteForm(request.POST) if form.is_valid(): form.create(validated_data=request.POST) Errors: TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' TypeError at /admin/cliente Field 'seguimento' expected a number but got [3]. -
React.js: posts.map is not a function
I'm getting this error when running my app and i don't know why! i have this react component that's getting data from a djagno api that's consists of a title, body for the post, slug, image, date (day and month) and a category. i have defined posts as an array but it's still giving me an error that's posts.map is not a function. i hope someone can help me with this on cuz i have spent 3 days trying to figure out what's wrong with this code import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { Link } from 'react-router-dom' const Post = () => { const [posts, setPost] = useState([]); useEffect(() => { const fetchPost = async () => { try { const res = await axios.get(`${process.env.REACT_APP_API_URL}/api/post/`); setPost(res.data); console.log('data', res.data); } catch (err) { } } fetchPost(); }, []); const capitalizeFirstLetter = (word) => { if (word) return word.charAt(0).toUpperCase() + word.slice(1); return ''; }; const getPost = () => { let list = []; let result = []; posts.map(blogPost => { return list.push( <div className="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div className="col p-4 d-flex flex-column position-static"> <strong className="d-inline-block mb-2 text-primary">{capitalizeFirstLetter(blogPost.komite)}</strong> … -
url from UpdateView is not working in CreateView django
The question is that why can't I put a link(redirect to post_edit.html, using UpdateView) in the post_new.html(CreateView)? However, it works to put the link in the post_detail.html(DetailView). Is there any restrcition between Views? -
How to generate a PDF from content on the page - Django
I've got a model with a field for a EULA (it's kind of long, maybe about 8500 characters). This EULA is rendered to the page like so: <div class="collapse" id="library-eula"> <div class="card"> <div class="card-body"> {{ library.eula|markdownify|safe }} <a href="#" class="btn btn-primary" role="button"> Download PDF </a> </div> </div> </div> That Download PDF button is meant to be for downloading the content in the card (library.eula) as a PDF. I started with the example from Django's docs. I copied the code directly from that page. When I use this code as is in a CBV with a get method (eg, as a test -> p.drawString(100, 100, "Test page")) and then hook up a URLconf: # Download a PDF path('download/pdf', DownloadPDFView.as_view(), name='download-pdf'), And add this to the template: <a href="{% url 'download-pdf' %}" class="btn btn-primary" role="button"> Things work fine... But I'm having a hard time figuring out how to actually stick the library.eula string into the PDF. I've tried a few things but I feel like I'm going nowhere.