Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Postgresql - password authentication failed for user
Well, I've been working on a project on Django, but a friend of mine was facing a problem so he sent me his project (The entire folder). Anyway, I tried to run the server but it didn't work. I tried to change the password and the username from the settings file, and when I tried to access the user, the username was changed (as the sql shell recognized it, I think ¯_(ツ)_/¯), but whenever I try to login with the password I wrote in the settings file it produces the following error: django.db.utils.OperationalError: FATAL: password authentication failed for user "Youssef" Here's the DATABASE part in the settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'Boards_django', 'USER': 'Youssef', 'PASSWORD': '000000', 'HOST': 'localhost', 'PORT': '5432', } } BTW, the database is recognized by the PgAdmin4: Any idea what should I do??? Side note: I can't access the user, hence I'm not able to use any of the commands of postgresql -
Django admin form, thows error while set ArrayReference field, Djongo
I'm newbie in Django, I got an error when trying to set ReferenceField to Record This is models: from djongo import models class Record(models.Model): _id = models.ObjectIdField(primary_key=True) text = models.TextField() attatched_file = models.FileField() file_type = models.TextField() class Diary(models.Model): _id = models.ObjectIdField(primary_key=True) title = models.TextField() records = models.ArrayReferenceField(to="api.Record", on_delete=models.CASCADE) Can someone tell whats am I doing wrong? -
django: Issue with the url paths
I need little help with how to redirect the link to the right url. I have one object that has 2 categories rents and sales. When the form is submitted I can successfully redirect the user to the right place but that is from the views --- return redirect(category +'/'+ listing_id) --- Any trick how can I do the same from the HTML? Any help is appreciated! urls. path('rents/',rents, name = 'rents'), path('rents/<int:pk>',RentView.as_view(), name = 'rent'), path('sales/',sales, name = 'sales'), path('sales/<int:pk>',SaleView.as_view(), name = 'sale'), html: First one has url localhost/dashboard/sales/1 . It should be localhost/sales/1, but I'm not sure how to remove that dashboard. Since the current page is dashboard. <td class="column3"><a href = "{{contact.category}}/{{ contact.listing_id}}" ><button class='btn-view'>View</button></a></td> Second case: I have two categories: sales and rents. It seems to work if I leave it like this, but if there is a query from rents it will redirect the URL to sales. <td class="column3"><a href = "{% url 'sale' contact.listing_id %}" ><button class='btn-view'>View</button></a></td> -
How To Get A Free Customized And Full Betting Html, Css, python or Django Templates For My Design
I developed a betting application with django and python and the template am working on is very displeasing and bad (it look too static and nothing dynamic about it). i need help with a free html template- am just a little Woman and a simple Lady that have given everything to python django and begin to learn web and app development. i need a free templates for a betting website and i will be glad if there is anyone that can help. i have to to get this templates from online but it seems not possibe am been ask to buy the few i saw online and i dont have cash for that seriously. -
Django Model Forms - Adding widget that assigns css class causes browse file button to disapear for FileField
for some reason if I try to assign a css class to a model form filefield the search button disappears forms.py class CsvForm(forms.ModelForm): class Meta: model = Csv exclude = ('user',) labels = {'file_name' : 'Browse'} widgets = { 'file_name': forms.TextInput(attrs={'class': 'form-control'}), } models.py 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) If I delete the widget, the button reappears and I can search for files again. Why does this happen? -
How to use Flutter's Streambuilder with Django Rest Framework?
I am very new to coding. I want to know how to use Flutter's Streambuilder with a Django Rest Framework as backend? I know to use Streambuilder, but how do I code for the same with Django? -
Why do django migrations temporarily take disk space?
Setup: Django (2.2.18) and Postgres (9.5) in one server, same disk. Migrations are altering 1 table (adding and removing fields). I'm not sure if my question is correct but I ran into a problem with my setup above while applying migrations. Error is from psycopg2: DiskFull: could not extend file "base/167296/1842042": wrote only 4096 of 8192 bytes at block 161 HINT: Check free disk space. Current disk usage is 14G out of 20G. We resolved the issue by deleting a few files and running the migrations again. We observed that the disk usage temporarily increased to about 96% of 20G then went back to 14G. Now we need to do something so the issue doesn't happen again. My question is: if we move the database to something like RDS, will it be enough? I ask because I'm not sure if it's the database size that temporarily inflates or if it's django that creates temporary files on disk. In the second case, it would mean that moving the database will not actually solve the issue. I'd appreciate references as I couldn't find anything on this on the django docs (or I'm blind). -
Download a file that is uploaded on Django admin page on the user's view
I looked everywhere for a solution, I am creating a Capture The Flag game using Django, I have everything ready, but the download part. I want to let the people who are playing can be able to download the files I upload from my side on the Django Admin page. models.py class Questions(models.Model): Qid = models.IntegerField(default='0') Qtitle = models.CharField(max_length=70) Qdes = models.CharField(max_length=1000) Hint = models.CharField(max_length=500, default="") file = models.FileField(blank=True) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('404', views.error, name='error'), path('register', views.signup, name='signup'), path('about', views.about, name='about'), path('login', views.login1, name='login1'), path('profile', views.profile, name='profile'), path('QUEST', views.Quest, name='Quest') quests.html <a target="_blank" href="_Blank" class="btn btn-outline-secondary btn-shadow"><span class="fa fa-download mr-2"></span>Download</a> <a href="#hint" data-toggle="modal" data-target="#hint" class="btn btn-outline-secondary btn-shadow" onclick="getHint({{question.Qid}})"><span class="far fa-lightbulb mr-2"></span>Hint</a>``` -
Why does django rest framework app works locally, but can only do GET requests when deployed to heroku?
I cannot do methods other than GET when accessing the API on heroku. Else, I get a 500 internal server error. I suspected that it had to do with permissions: REST_FRAMEWORK = { 'TEST_REQUEST_DEFAULT_FORMAT': 'json', # Authentication Scheme 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), # Permission Policies 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } However, when I tried commenting out the DEFAULT_AUTHENTICATION_CLASSES, I still couldn't log in. I am using django-rest-auth if that helps (https://django-rest-auth.readthedocs.io/en/latest/installation.html) Again, it works on my local server (I haven't tried heroku local though). What else am I missing? -
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; …