Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Im using django-bootstrap4 in my Django project, how would I add the option for "$enable-responsive-font-sizes"?
Im just having a few issues trying to get this to work. --please correct me if I'm wrong-- But Django-bootstrap4 has a pretty recent release of bootstrap meaning enable-responsive-font-sizes should be included. I have added the option $enable-responsive-font-sizes:true; to my scss file, but it does not seem to change anything. I feel that im missing something here. Any help would be greatly appreciated. -
If a user post is potentially offensive then set Active to false
I don't want users to be able publish offensive comments on my posts. I know a way of censoring out s***, f***, c*** etc. But if you apply a blanket ban to offensive words then you may unintentionally end up banning a word such as Scunthorpe (a place in the UK) because it contains an offensive substring. In forms.py I want to set the comment active property to false if the comment potentially contains an offensive word. Therefore I could manually check any potentially controversial posts. models.py class Comment(models.Model): #The foriegn key is linked to the ID field in the Post model #id = models.IntegerField(primary_key=True, blank=False) post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') nameid = models.ForeignKey(User,on_delete=models.CASCADE,related_name='commentsid') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on= models.DateTimeField(default = timezone.now()) active = models.BooleanField(default=True) forms.py I have tried setting active to false in at least 4 different ways but have so far had no luck. Does anyone have any suggestions? def clean_body(self): body = self.cleaned_data.get("body") active = active if "f***" in body or "s***" in body : self.data['active'] = False self.fields['active'].initial = False self.cleaned_data.get("active")=False form.fields['active'].initial = False return body -
How can I create 2 forms simultaneously in just one view in django
I have two forms in the same template('index.html'), one form is to contact me and when the user send the form I receive an email. And the Other form is to 'register' in the system, so then i can enter in contact. The problem is that the two forms are in the same template and I want put them in the same view. This is the way that my view is. class IndexView(FormView): template_name = 'index.html' form_class = ContatoForm success_url = reverse_lazy('index') def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['servicos'] = Servico.objects.order_by('?').all() context['funcionarios'] = Funcionario.objects.order_by('?').all() context['portfolios'] = Portfolio.objects.order_by('?').all() context['testimonials'] = Testimonial.objects.order_by('?').all() return context def form_valid(self, form, *args, **kwargs): form.send_mail() messages.success(self.request, 'E-mail enviado com sucesso') return super(IndexView, self).form_valid(form, *args, **kwargs) def form_invalid(self, form, *args, **kwargs): messages.error(self.request, 'Erro ao enviar e-mail') return super(IndexView, self).form_invalid(form, *args, **kwargs) This is the modelform that i want to put in the view class RegistroModelForm(forms.ModelForm): class Meta: model = Registro fields = ['nome', 'email', 'phone', 'area'] -
Trouble with simple Django programm
dear participants! I'm studying Python developer course at JetBrains Academy (hyperskill.org) with current project: HyperNews Portal. I'm stuck on stage 1 - Main page header with task descripted below. Description You're working on a college newspaper called Hypernews. You are comfortable in the digital world, so you came up with the idea of broadcasting the news online and decided to create a website for this. Creating the Hypernews site will be a long road, so let's take our first step forward and make the first page. For now, you won't have actual news on the site, so until that happens you can respond to the users with the "Coming soon" message. Objectives Create the first handler for your server. If you start the project on your computer with python manage.py runserver command, your server should respond with the text "Coming soon" at the address localhost:8000. The problem I'm getting the disired result: after start of the project on my computer with "python manage.py runserver" command, my server is responding with the text "Coming soon" at the address localhost:8000. But EduTools plugin is responding "Wrong answer in test #1". I'm trying to understand why server of academy see wrong answer in … -
MultiValueDictKeyError when trying to change profile image
views.py every thing working okay just image cant be changed and i dont why so, i think there is some fuction or some thing like request.POST[image] to get an image template.html -
nothing is saved after updating form
I have a Candidat models and Experience_Pro models as shown below with fk relation between them . i can register or login a candidat(user) and a profil page with firstname and lastname of that candidat shown, and a form for Experience_Pro for the user to add if he does have one . but when i enter all the info in the Experience_Pro form and click update nothing is added to candidat I don't know what i am missing but the form is showing with no errors and even after i update the profile no errors but nothing is saved to candidat models.py class Candidat(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) experience_Pro = models.ForeignKey('Experience_Pro' ,on_delete=models.CASCADE,blank=True, null=True,default='') class Experience_Pro(models.Model): annee_debut = models.IntegerField() annee_fin = models.IntegerField() description_exp_pro = models.TextField(null=True,blank=True) forms.py class UpdateCandidat(forms.ModelForm): class Meta: model=Candidat fields=['experience_Pro'] class CreateExperience_Pro(forms.ModelForm): class Meta: model=Experience_Pro fields='__all__' views.py @login_required def profil(request): exp_form = CreateExperience_Pro() c_form = UpdateCandidat() if exp_form.is_valid(): exp = exp_form.save() candidat = c_form.save(commit=False) candidat.save(experience_Pro=exp) return redirect('profil') context={ 'exp_form':exp_form } return render(request ,'candidats/profil.html',context) profil.html <h1>Profil Candidat</h1> <p>Prenom: {{ user.first_name }}</p> <p>Nom: {{ user.last_name }}</p> <p>Email: {{ user.email }}</p> <form method="POST" action=""> {% csrf_token %} {% comment %} {{ c_form }} {% endcomment %} {{ exp_form }} <input type="submit" value="Update"> … -
Customer User Model with UUI PK cant login to admin site in Django 3.0, PostgreSQL
My customer user model looks like this : class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) email = models.EmailField(unique=True) is_staff = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return self.is_admin def __str__(self): return self.email class Meta: db_table = 'login' When I try to login to admin after doing manage.py createsuperuser , it throws the following error : ProgrammingError at /admin/ operator does not exist: integer = uuid LINE 1: ...NER JOIN "login" ON ("django_admin_log"."user_id" = "login".... I understand this has to do with PostgreSQL being strongly typed and Django not wanting to assume incoming field type. I want to go around this issue as many customer user tutorials out there specify UUID type primary key and don't seem to run into this problem when the steps ask you to login to admin and test it out. -
opposite of get_field_display in django?
I have a model class Book(models.Model): name = models.CharField(max_length=250, null=True, blank=True) CATEGORY_CHOICES = ( (1, 'Fiction'), (2, 'Non-Fiction'), ) category = models.PositiveSmallIntegerField(choices=CATEGORY_CHOICES) I know that if I have a value 1 then I can use get_category_display(1) -> Fiction. But is there a way to do the opposite in django? i.e. getting the integer, given the display name? Currently I am doing it like this category = "Fiction" category_integer = dict(map(reversed, Book.CATEGORY_CHOICES))[category] -
How to do price sorting of product in Django (Python)?
I want to sort the product according to their prices, stored in the variable after extracting from a website. The variable will contain the following details- datamatch - [({'name': 'Redmi K20 Pro', 'link': 'www.exp.com', 'imglink': 'www.exp.com', 'price': '26999', 'SITE': 'flipkart'}, {'name': 'Redmi Note 7 Pro ', 'link': 'www.exp.com', 'imglink': 'www.exp.com', 'price': '13999', 'SITE': 'flipkart'})] The name of the html file is result.html and its code is given below.- result.html- {% for ab in datamatch %} {% for c in ab %} {% for a in c|dictsort:"a.price" %} <div class="center"> <div class="a"> <div class="p"> <div class="card horizontal col m4 "> <div class="card-stacked"> <div class="card-content"> <div class="animated bounce"> <div class="card-title black-text text-darken-4"><h4 style="text-align:left;">{{ a.name}}</h4><h5 style="text-align:left;"> {{ a.SITE }}</h5> <ul style="text-align:left;"> <li> Category: {{ a.link }} </li> <li> Sale Price: {{ a.price }} </li> <li> Image link: {{ a.imglink }} </li> <li> Availability: <span class="new badge green" >{{ a.imglink }}</span> </li> </ul><a class="waves-effect waves-light btn m" href="{{ a.URL }}" style="align:right;"><i class="large material-icons right">play_arrow </i>View</a> </div> </div> </div> </div> </div> </div> </div> </div> {% endfor %} {% endfor %} {% endfor %} ` I tried with the above code and it returns nothing. but, as soon as i delete the (|dictsort:"a.price") it retuns the … -
default date and time for DateTimeField in django
in my models, I have : date_time = models.DateTimeField(auto_now = True) This is surely works and adds current date and time for new records that get created. However, I want to set the default date and time for existing records as 01/01/2020 00:00:01. if I try to add a default along with auto_now, I get an error stating auto_now and default are mutually exclusive. -
format of returned result for .objects.filter(name__containe=data) without quotes sign
I have written a code by django in which a user can search for a word in a table of database. My problem here is when I print the returned results, they contain quotations. How can I omit them? def My_data_filed(request): form = data_filed_Form(request.POST or None) data = None download_form = None if request.method == 'POST': if form.is_valid(): data_g = form.cleaned_data.get('g') data = list(data_filed.objects.filter(g__contains=data_g).values()) print(data_filed.objects.all().values()) download_form = data_filed_DownloadForm(initial={ 'g': data_g, }) return render(request, 'search_report.html', { 'form': form, 'data': data, 'download_form': download_form }) The output of this code is like: 'Creator': 'Davide' But I just want to have: Davide Whats wrong in my effort? -
How much Django is faster to load 20,000 QuerySet?
I just want to know that how much Django is faster. if my model has 20,000 objects and I want to load them all in a single request like. data = my_model.objects.all() Then how much it takes time to loads on the client browser if he/she requesting the my_model data. if we load only 10 list-objects does it is more than faster than the first approach? data = my_model.objects.all()[:10] Which is faster? -
Generate random test image for Django tests
I have a function for generating test images for Django tests: def generate_test_image() -> SimpleUploadedFile: """ Generates simple test image. This seem work with all image validators. """ small_gif = ( b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04' b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02' b'\x02\x4c\x01\x00\x3b' ) return SimpleUploadedFile('small.gif', small_gif, content_type='image/gif') And I have an another function based on library imagehash that creates image hash for images in order to store it in db and not allow to upload one image twice. def create_image_hash(image: BinaryIO, raise_errors: bool = False) -> Optional[imagehash.ImageHash]: """ Creates image hash on image file. """ try: image_hash = imagehash.average_hash(PIL.Image.open(image)) except PIL.UnidentifiedImageError as err: if raise_errors: raise err from err return None return image_hash This function generates hash for test image – 0000000000000000 Is it any way to generate test image different enough to have different image hash on these images? I have tried following: def generate_random_test_image(size: int = 150) -> SimpleUploadedFile: """ Generates random test image. """ base = bytearray( b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04' b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02' b'\x02\x4c\x01\x00\x3b' ) random_part = bytearray(random.getrandbits(8) for _ in range(size)) return SimpleUploadedFile('small.gif', base + random_part, content_type='image/gif') But regardless of the size it finally makes the same image hash – 00000000000000 Any ideas? Thank you! -
Manually add choices from admin login in Django
I want to add choices manually to choice field in a model from admin account in Django. Is there anyway I can do that? -
Django admin history view is distorted
I'm new to django & I used SimpleAdminHistory to display history. Class class EmployeeAdmin(ImportExportModelAdmin, NestedModelAdmin, SimpleHistoryAdmin): Result As you can see the layout in the view is all distorted & I can't seem to figure why this could be happening. I'm using the following packages Django 2.2.11 django-simple-history 2.8.0 Any help or sense of direction will be appreciated. -
Django model foreign key on_delete=null but foreign key is deleted anyway
I am trying to change a foreign key reference's on delete value from cascade to null like so: created_by = models.ForeignKey(CustomUser,on_delete=models.SET_NULL, null=True) When I test this by deleting a record from CustomUser I get a count of the objects in the Games table before and after performing the delete. p = Games.objects.count() print(p) #outputs 100 cu = CustomUser.objects.get(pk=2) cu.delete() p = Games.objects.count() print(p) #outputs 98 I have tried using the other values for on delete but the only one that doesn't delete the rows from the database is protect. It instead raises a protection error raise ProtectedError( django.db.models.deletion.ProtectedError: ("Cannot delete some instances of model 'CustomUser' because they are referenced through a protected foreign key: 'Games.created_by'", <QuerySet [<Games: 181 79 None>]>) -
Django custom login decorator checking if session exists
I am trying to implement a custom login in Django utilizing a custom auth Backend. These are the steps Initialize session when the user is authenticated write a custom decorator to wrap in the views (login_required) I get: AttributeError: 'NoneType' object has no attribute 'session' from django.contrib.auth.decorators import user_passes_test def login(request): user = authenticate(username=username,password=password) if user: request.session['user_id'] = user.pk def login_required_custom(request): return request.session.get('user_id') or False @user_passes_test(login_required_custom, login_url='/login/') def HomePage(request): return -
Adding additional requirements to access admin site in django
Basically by default in order to access the admin site in django you need the user.is_authenticated and user.is_staff attributes. I'm looking to add an additional one called user.is_elevated. If it's false the plan is you'll be redirected to a separate login page or maybe a popup window to enter a password idk. If it's true you can use admin as normal. I see a bunch of stuff saying "this is the default way" but can't find where I go to implement my own thing. Any help is greatly appreciated. Cheers, Cap -
django rest not showing one of the endpoints in API
One of the viewsets named 'wallet' is not showing in the main API page. I checked the routers registered in the urls, but I'm not finding the issue. SiteWallet model: class SiteWallet(models.Model): owner = models.OneToOneField(SiteUser, on_delete=models.CASCADE, related_name='SiteWallet') balance = models.DecimalField(max_digits=40, decimal_places=2, default=0 , blank=True, null=True) class Meta: verbose_name = 'Wallet' verbose_name_plural = 'Wallets' def __str__(self): return f"{self.owner} : {self.balance}$" def get_absolute_url(self): return reverse("Wallet_detail", kwargs={"pk": self.pk}) def deposit(self, amount): self.balance += amount self.save() WalletTransaction.objects.create_deposit_transaction(self, amount) def withdraw(self, amount): if self.withdraw_valid(amount): self.balance -= amount self.save() WalletTransaction.objects.create_withdraw_transaction(self, amount) else: raise Exception("Not enough $") def withdraw_valid(self, amount): if self.balance >= amount: return True else: return False WalletSerializer: class WalletSerializer(serializers.ModelSerializer): class Meta: model = SiteWallet fields = ['balance'] WalletViewSet: class WalletViewSet(mixins.RetrieveModelMixin ,viewsets.GenericViewSet): """endpoint for viewing the balance of wallet or charging it""" serializer_class = WalletSerializer permission_classes =[IsOwnerOrReadOnly] queryset = SiteWallet.objects.all() @action(detail=True, methods=['POST']) def charge_account(self, request): wallet = self.get_object() wallet.deposit(request.data['amount']) return Response(status=status.HTTP_200_OK) @action(detail=True, methods=['POST']) def withdraw(self, request): wallet = self.get_object() wallet.withdraw(request.data['amount']) return Response(status=status.HTTP_200_OK) and the app's urls: router = routers.DefaultRouter() router.register(r"Users", SiteUserViewSet, basename="Site Users") router.register(r"Wallet", WalletViewSet, basename="wallets") router.register(r"Bank accounts", BankAccountViewSet, basename="bank account") router.register(r"Wallet transaction", WalletTransactionViewSet, basename='wallet transaction') urlpatterns =[ path('login/', views.LoginView.as_view(), name='login'), path('logout/', views.LogoutView.as_view(), name='logout') ] + router.urls I'm new to Django, if there's any part … -
I am new to graphql and I am finding difficulty in using schema from two different apps in django-graphql?
app1 hero schema.py import graphene from graphene_django import DjangoObjectType from .models import Hero class HeroType(DjangoObjectType): class Meta: model = Hero class Query(graphene.ObjectType): heroes = graphene.List(HeroType) def resolve_heroes(self, info, **kwargs): return Hero.objects.all() app2 product schema.py class ProductType(DjangoObjectType): class Meta: model = Product class Query(object): allproducts = graphene.List(ProductType, search=graphene.String(),limit=graphene.Int(),skip=graphene.Int(), offset=graphene.Int()) def resolve_allproducts(self, info, search=None, limit=None, skip=None, offset=None, **kwargs): # Querying a list of products qs = Product.objects.all() data = [] if search: filter = ( Q(name__icontains=search)| Q(price__icontains=search) ) qs = qs.filter(filter) if skip: qs = qs[skip:] if limit: # qs = qs[:limit] qs = qs[int(offset):(int(offset) + int(limit))] return qs In main project schema.py, how do I call schema from app1-hero and app2-product? -
How can I prevent my site users from publishing posts that contain swear words?
I saw this question asked on Reddit but sharing code on Reddit quickly gets messy so decided to share the answer here (look at my comment below). -
getting a queryset ordered by a field while removing duplicates based on another field
I'm trying to create a simple chat app for my website by modifying directmessages. The model: class Message(models.Model): content = models.TextField(_('Content')) sender = models.ForeignKey(AUTH_USER_MODEL, related_name='sent_dm', verbose_name=_("Sender"),on_delete= models.CASCADE) recipient = models.ForeignKey(AUTH_USER_MODEL, related_name='received_dm', verbose_name=_("Recipient"),on_delete= models.CASCADE) sent_at = models.DateTimeField(_("sent at"), null=True, blank=True) read_at = models.DateTimeField(_("read at"), null=True, blank=True) The function which returns all conversation partners as a set: def get_conversations(self, user): all_conversations = Message.objects.all().filter(Q(sender=user) | Q(recipient=user)) contacts = [] for conversation in all_conversations: if conversation.sender != user: contacts.append(conversation.sender) elif conversation.recipient != user: contacts.append(conversation.recipient) # To abolish duplicates return list(set(contacts)) What I'm trying to achieve is getting a set of contacted users ordered by every conversation's "sent_at" field in order to sort the conversations based on last sent message. I wonder if there is a way to solve it by single query if not, what would be the best approach. -
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module on MacOS
I've been working on this Django project for some time now and recently I've connected my project to a MySQL database. It worked just fine one test project and was working fine on the main project until recently it started showing some sort of error. And yes I pip installed mysqlclient, pymysql and a bunch of other modules. Usually, the fix is to download some file on your computer for mysqlDb but that only works for windows. Can anyone help me with this problem for macOS, please? (Most of the answers are outdated and for python2, but I am working in python3) Command I typed: python manage.py runserver Error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 16, in <module> import MySQLdb as Database File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line … -
Why is my form not retrieving any data in django
I am trying to combine two input json data for a class based django rest framework view. I am feeding in data in this format { "profile": { "phone": "9841101115", "email": "nirjalpaudl543sddsd12@gmail.com", "bio": "I am the admin of the site", "status": "AWY", "address": "Pepsicola, Kathmandu" }, "user": { "username": "sampanna12", "password1": "test12345", "password2": "test12345" } } The error shown suggests that data was never retrieved by the serializers. The response i get is { "Error": "Something went wrong while making a user", "message": { "username": [ "This field is required." ], "password1": [ "This field is required." ], "password2": [ "This field is required." ] } } My is getting the data but not my form enter image description here My serializer.py looks like from rest_framework import serializers from django.contrib.auth.models import User from . import models class UserSerializer(serializers.ModelSerializer): password1=serializers.CharField( write_only=True, min_length=8, required=True, style={ "input_type":"password" } ) password2=serializers.CharField( write_only=True, min_length=8, required=True, style={ "input_type":"password" } ) class Meta: model=User fields=["username","password1","password2"] class ProfileSerializer(serializers.ModelSerializer): user=UserSerializer() class Meta: model=models.Profile fields=['phone','email','bio','status','address','user'] My views.py looks like from django.shortcuts import render from rest_framework.decorators import APIView from django.contrib.auth.models import User from rest_framework.response import Response from . import serializers,models # Create your views here. class UserApi(APIView): def get(self,request, format=None): allusers=models.Profile.objects.all() … -
Django common comment model to use in different apps
I am creating a project that requires comments in multiple apps like blog, wikis, and pages. I have a commons app that contains all common models. How do I have a Comment model that's common to all apps? commons/models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments') body = models.TextField() parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) blog/models.py class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') content = models.TextField() wikis/models.py class Wiki(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='wikis') content = models.TextField() From what I researched, I have the following options, Three Comment models three apps. One Comment model in commons app with ForeignKey relations to the other apps (which I believe will cause circular import issues) and end up with a comment table with multiple columns like blog_id, wiki_id, and page_id. Use Django's GenericForeignKey relationships. I don't want to do 3. But out of 1 and 2 I would like to know which is the most efficient way to handle this without repeating codes and adding unnecessary database joins. Or is there a better way to do this?