Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework: exclude results when nested serializer is empty
I have a nested serializer that works, but I would like to exclude instances where the nested serializer is empty. The filtering I'm using on the nested serializer works, but currently this code returns all Sites, most of which have empty site_observations arrays when filters are applied. I would like to return only Sites that contain site_observations. I have tried a SerializerMethodField for site_observations but have the same issue. Using DRF 3.12 Relevant models are Site, and Observation which has FK to site, with related field=site_observations serializers.py class FilteredObsListSerializer(serializers.ListSerializer): def to_representation(self, data): projName = self.context["projName"] # this is my filter which works data = filter_site_observations(data, self.context["request"], projName) return super(FilteredObsListSerializer, self).to_representation(data) class ObsFilterSerializer(serializers.ModelSerializer): class Meta: list_serializer_class = FilteredObsListSerializer model = Observation fields = "__all__" class SiteSerializer(GeoFeatureModelSerializer): site_observations = ObsFilterSerializer(many=True) class Meta: model = Site geo_field = "geometry" fields = ("id", "name", "geometry", "site_observations") views.py class SiteList(generics.ListAPIView): queryset = Site.objects.all().order_by("pk") serializer_class = SiteSerializer # this is for filtering Observations on segment of an url: def get_serializer_context(self): context = super(SiteList, self).get_serializer_context() context.update({"projName": self.kwargs["name"]}) return context How can I exclude Sites where site_observations is an empty list? Thanks. -
Django and Ajax: add to Favourites button in a for loop functioning and making changes to database but not changing colour/name appropriately
I'm having difficulty understanding why my favourite buttons will not change colour and name when clicked to match the data in the database. I presume it is due to the way I have set up the 'is_fav' boolean variable but I've been unable to work out a fix. Any help is greatly appreciated! the view: def favourite_unfavourite(request): html = None #if request.method == 'POST': activity_id = request.POST.get('activity_id') activity = get_object_or_404(TherapyActivity, id=activity_id) #is_fav = False if activity.favourites.filter(id=request.user.id).exists(): activity.favourites.remove(request.user) is_fav = False else: activity.favourites.add(request.user) is_fav = True context = { 'Activity': activity, 'is_fav': is_fav, 'value': activity_id } if request.is_ajax(): html = render_to_string('main/favourite_section.html', context, request=request) return JsonResponse({'form': html}) page html: {% extends "main/index.html" %} {% block title %} <h1>View All</h1> {% endblock %} {% block content %} {% for activity in activities %} <div class="col-md-7 d-flex justify-content-between"> <li><a href="{{activity.get_absolute_url}}">{{activity.name}}</a> <br> {{activity.description}} </li> <div id="favourite-section"> {% include 'main/favourite_section.html' with activity=activity %} </div> </div> {% endfor %} {% endblock %} included section: {% if request.user.is_authenticated %} <form action="{% url 'account:favourite_unfavourite' %}" method="post"> {% csrf_token %} {% if fav %} <button type="submit" id="favourite" name="activity_id" value="{{ activity.id }}" class="btn btn-danger">Unfavourite</button> {% else %} <button type="submit" id="favourite" name="activity_id" value="{{ activity.id }}" class="btn btn-primary">Favourite</button> {% endif %} </form> {% … -
Heroku deploy with django database issue
i need some, did lot of research but cant find the solution. i just deployed my app into heroku, everything seem to work just fin, but the cant access to the database from the APP, admin looks empty. But the database is there on heroku when i check it database in heroku Settings.py Whitenoise whitenoise 2 database conection static urls.py static in URL i think maybe some config with the connection is missing, but i dont know what else to do... thanks in advanced for any help! -
Making API calls for authentication tasks in Angular
I'm trying to build an authentication system using Django, Django rest framework, angular, and I have been based on Dj-rest-auth to handle user registration and authentication tasks. I finished implementing the back-end level, but I'm getting stuck on how can I make API calls to register new users, log in as an authenticated user, and other queries such as forgot password, and email confirmation. Would you please help me to implement that in service.ts? -
Problem installing Pandas and Numpy on Heroku
I am trying to install Django 3.0.5 on heroku with numpy==1.18.3and pandas==1.0.3 libraries included in the requirements.txt file but it keeps running into an error. I have python-3.7.10 in my runtime.txt I ran the install command, but it gives me the following errors. git push heroku main and I am getting this error: Counting objects: 100% (107/107), done. Delta compression using up to 12 threads Compressing objects: 100% (95/95), done. Writing objects: 100% (107/107), 223.74 KiB | 6.99 MiB/s, done. Total 107 (delta 19), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python-3.9.6 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.9.6 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting asgiref==3.2.7 remote: Downloading asgiref-3.2.7-py2.py3-none-any.whl (19 kB) remote: Collecting certifi==2020.4.5.1 remote: Downloading certifi-2020.4.5.1-py2.py3-none-any.whl (157 kB) remote: Collecting chardet==3.0.4 remote: Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB) remote: Collecting coverage==5.5 remote: Downloading coverage-5.5-cp39-cp39-manylinux2010_x86_64.whl (243 kB) remote: Collecting Django==3.1.12 … -
Is Mysql good for Django?
Do you think I can use MySql with Django, cuz a friend tells me it's not the best choice to use with Django framework -
Getting CSV saving in the document folder
I know this question probably appeared million times, but I cannot get my code to work. I want to upload csv to a folder, so I can make further operations on it. I think the problem might be in my HTML code, but not sure where. Folder I want to save it to is documents/, I did not add it to settings.py but I saw other people were not adding it there either. My code is as per below: Main urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from mainsite import views as main urlpatterns = [ path('admin/', admin.site.urls), path('', main.index, name= 'index'), path('contact/', include('contact.urls')), path('explanation/', include('modelexpl.urls')), path('uploads/', main.model_form_upload, name='model_form_upload') ] App urls.py from django.shortcuts import render from django.http import HttpResponse from django.urls import path from mainsite import views # Create your views here. urlpatterns = [ path('', views.index, name='index') ] App's models. from django.db import models # Create your models here. class Document(models.Model): description = models.CharField(max_length=200, blank= True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) App's views from django.shortcuts import render from django.http import HttpResponse from mainsite.models import Document from mainsite.forms import DocumentForm # Create your views here. def index (request): placeholder = {'test' : … -
Can't import image in Django
Here is my project structure I'm trying to display the image from the static folder but it can't be displayed. I also tried to mention the static folder in the settings.py file as below: Here is how I'm calling the image from the base.html file. I'm not sure what is wrong, I tried to search but the google sources can't help. -
How to add a horizontal rule in bootstrap?
I'm trying to add a horizontal rule in-between my divs. Here is my code. Div("Name", css_class='col-sm-12'), Div("Address", css_class='col-sm-6'), Div("Favorite_Movie", css_class='col-sm-6'), <hr> <-- Horizontal rule would go here. -
Key encyption, front-end back-end question
I have a front end which has some api credentials which are needed to receive information for the front-end. I also want to store these credentials in a database so that the user does not need to enter these api credentials with every log in, rather the api credentials are 'there'. How should these api keys be stored in the back end and then de-crypted in the front-end? -
Django: On button/link click, send an API request, fetch data, save it in a variable, and put variable in textarea/textbox without refreshing page
I've been breaking my head attempting to come up with a simple solution to something I had in mind. What I'd like to have is: User clicks on a button or a link disguised as a button to reveal information. The server will then send an API request to https://randomuser.me/api, which is outside of the domain. The first name of the random user in the API will be stored in a variable. The variable storing the first name will then be put in the textarea. The button's text will change to "hello" as a greeting instead of just "button" and will not be clickable from now on. OR TO BE FANCY: It can have a timer counting down from 20 minutes. The div that was hidden previously will now show up with the updated button and the textarea filled in with the first name of the random person, ready for the user to copy. I know I can use Python to get requests results from the server. I just don't know how to implement that with Django with the features I want above, especially without Django reloading/refreshing the page. The HTML page: <div> <a href="#" class="button" onclick="showButtonDetails()">button</a> <div id="showDIV" style="display: … -
Custom Django User not saving
So I'm trying to create a user with many fields. I followed a tutorial on how to create a custom user model by inheriting from the base user class and then creating a user manager. I had one of my past professors take a look at it and he couldn't find anything that would keep it from saving, kind of at a loss here. class UserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser Full_Name = models.CharField(max_length=200) industry_type = models.CharField(max_length=200) presenter = … -
Deployment Error Heroku [Remote rejected] master -> master (pre-receive hook declined)
I am trying to deploy my app in Django/Heroku but I am having this issue while doing git push Heroku master. This is the error I am getting after this command. Enumerating objects: 654, done. Counting objects: 100% (654/654), done. Delta compression using up to 8 threads Compressing objects: 100% (637/637), done. Writing objects: 100% (654/654), 10.77 MiB | 525.00 KiB/s, done. Total 654 (delta 138), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: ! Requested runtime (python-3.6.8) is not available for this stack (heroku-20). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to warm-taiga-11044. remote: To https://git.heroku.com/warm-taiga-11044.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/warm-taiga-11044.git'``` -
Djanto Singnals is not triggering through admin panel
I have a library that syncs some models with the s3 bucket, so, when someone deletes some row, it should receive the signal and activate the function. Here is the function: @receiver(post_delete) def on_object_deletion(sender, instance, **kwargs): """Upload deleted object to cloud if it is part of synced model""" deletion_time = datetime.datetime.now() # Retrieve the metadata (app and model name) for the model contenttype = ContentType.objects.get_for_model(model=instance) # Skip unnecessary database lookup (never syncs its own models) if contenttype.app_label == "lakehouse_sync": return syncmodel = SyncModel.try_retrieve_model(contenttype.app_label, contenttype.model) if not syncmodel: return # Raise exception if the instance is not BaseSyncModel. # Should be caught during clean() though. if not isinstance(instance, BaseSyncModel): raise Exception("Cannot sync a model that does not inherit BaseSyncModel") # Manually update the timestamp so the lakehouse can merge data instance.updated_at = deletion_time # Write the serialized object to the cloud blacklist = syncmodel.get_blacklist() serialized = Serializer.serialize_object(instance, blacklist) CloudActions.write_delete_file( contenttype.app_label, contenttype.model, serialized.getvalue() ) I didn't set the sender because I'll use this function for any model that inherits from the SyncModel. I'd like to ask for some help to figure out how to activate the signal when I made some deletions through the admin panel. I didn't understand the reason why … -
Maintaining history by soft deleting the row of table
Initially, I was hard deleting SQL rows. Now, I want to soft delete the row by adding a new column in table 'is_active'. if is_active=False, this means the row is deleted, and it is now part of history. But the concern is with the other tables where this table is referenced via a foreign key. earlier, when deleting this row, automatically deletes the record from other tables(model.cascade). Example; Table 1{ id uuid, is_active bool, . . } Table2{ id uuid, fk foreignKey(Table1, on_delete=models.cascade) } Table3{ id uuid, fk foreignKey(Table1, on_delete=models.cascade) } Now, if I will soft delete the table1(making is_active=False), then I have the following option, Add is_active columns to all other tables also which is referencing table1. and follow the same procedure to these tables as for table1. ISSUE: it will be a very hectic task, as some other tables might be pointing to table2, which in result may be referenced by some other tables. and we have manually set is_active=False for table2 and table3. QS. Is there any better approach for soft_deleting the table? like something like that, Table2{ id uuid, fk foreignKey(Table1, on_is_active_is_False=set.is_active=False), is_active bool } -
Django elasticsearch DSL with custom model fields (hashid field)
I have a model that uses django hashid fields for the id. class Artwork(Model): id = HashidAutoField(primary_key=True, min_length=8, alphabet="0123456789abcdefghijklmnopqrstuvwxyz") title = .... This is the related item of another model class ArtworkFeedItem(FeedItem): artwork = models.OneToOneField('artwork.Artwork', related_name='artwork_feeditem', on_delete=models.CASCADE) Now I'm trying to setup [django elasticsearch dsl] (https://github.com/django-es/django-elasticsearch-dsl) and to that end have the Document @registry.register_document class ArtworkFeedItemDocument(Document): class Index: name = 'feed' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } artwork = fields.ObjectField( properties={ 'id': fields.TextField(), 'title': fields.TextField( attr='title', fields={ 'suggest': fields.Completion(), } ) } ) class Django: model = ArtworkFeedItem fields = [] related_models = [Artwork] However, when I try to rebuild indices with python manage.py search_index --rebuild I get the following exception elasticsearch.exceptions.SerializationError: ({'index': {'_id': Hashid(135): l2vylzm9, '_index': 'feed'}}, TypeError("Unable to serialize Hashid(135): l2vylzm9 (type: <class 'hashid_field.hashid.Hashid'>)",)) Django elasticsearch dsl clearly does not know what to do with such a hashid field. I thought maybe I could just make my own HashIdField like from elasticsearch_dsl import Field class HashIdField(Field): """ Custom DSL field to support HashIds """ name = "hashid" def _serialize(self, data): return data.hashid then use it in 'id': HashIdField, but this gave me yet another exception elasticsearch.exceptions.RequestError: RequestError(400, 'mapper_parsing_exception', 'No handler for type [hashid] declared on field … -
Change sorting order for foreign key entity on Django
I would like to rearrange this dropdown to were profiles are sorted based on A-Z order based on the name. I would like to leave the string formatted in the same format it is now just have them sorted from A-Z. -
Nginx-ajax-django: 504 timeout error on page, error-log: upstream timed out (110: Connection timed out) , TTFB>1
I have a django application running on an nginx server which uses ajax to do asynchronous rendering of an html page. I have got the 504 gateway timeout tried almost every solution mentioned in stack overflow nothing worked out. In my application, I upload an excel sheet from which data is parsed, processed, pushed into database and then status of processing is displayed on an html page. I realized that first two to three rows of data are being processed normally and result is also being displayed correctly.For the remaining rows the backend process is happening correctly but ajax is not receiving the status message from django view. It is showing 504 error message. The error logs are showing upstream timed out error. I even included timeout:333333 in my ajax code. If I make async:false in ajax , process is slowing down and I am getting page unresponsive error message. By closely observing I realized that for processes which are incomplete TTFB is becoming more than 1. So can someone explain what to do? nginx.conf events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush off; tcp_nodelay on; keepalive_timeout 605; types_hash_max_size 2048; … -
Image url in django template doesnt work in production
I'm trying to show images in a one-to-many relationship with a Post model. The Post model is in a one-to-many relationship with a Category model. My code works with debug: True but fails in production. Can anyone see why? settings.py: import os BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEBUG = False models.py: class BlogImage(models.Model): b_img = models.ImageField("Blog Image", null=True, blank=True, upload_to="img/b", default='imagedefault.jpg') postimg = models.ForeignKey('Post', on_delete=models.SET_NULL, null=True) class Post(models.Model): ... category = models.ForeignKey('PortfolioCategory', on_delete=models.SET_NULL, blank=True, null=True) class PortfolioCategory(models.Model): category_name = models.CharField(max_length=100, unique=True) urls.py: from django.conf.urls.static import static ... urlpatterns = [...]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) html: {% for category in categories %} {% for post in category.post_set.all %} {% for img in post.blogimage_set.all %} <img src="{{ img.b_img.url }}" alt=""> {% endfor %} {% endfor %} {% endfor %} This code returns ValueError: The 'b_img' attribute has no file associated with it. I'm losing my marbles trying to make this work. Thanks in advance for anyone who can help ! -
Django's change password form (views.py)
I have an issue... I really dont know how to remove the help_text,label or wathever it is in the change_password form views.py . Please help me. Look the picture I linked for more information about ... enter image description here this is the picture , between the inputs you can see the text with markers, how can i remove it ? -
After adding an URL link, the text type and size changes automatically. How can I sort out this issue?
I have the following in django-ckeditor settings CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } and I have a simple model class Faq(models.Model): question = RichTextUploadingField() answer = RichTextUploadingField() Output screenshot below The font type and size change automatically to a smaller one after adding a link. You can see this in the above screenshot. It seems to me it automatically changes to the default setting. How can I access the default text setting? Can you please help me to troubleshoot this issue? I am using the django-ckeditor 6.1.0 version and Python 3.7. Thanks -
What are the current ways to get_absolute_url for django-mptt?
I read other questions, but I didn't find anything useful for Django 3, they just don't work. The link type is needed like this: post/categories/subcategories/**etc I think an adequate answer will be useful for everyone. Tell me how to do it for DetailView class Category(MPTTModel): title = models.CharField(max_length=255, verbose_name=_('Заголовок')) slug = models.SlugField(max_length=255, verbose_name=_('URL'), blank=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE) class MPTTMeta: order_insertion_by = ['title'] class Meta: unique_together = ['parent', 'slug'] verbose_name = _('Категория') verbose_name_plural = _('Категории') urls.py urlpatterns = [ path('category/<slug:slug>/', CategoryListView.as_view(), name='category_detail'), ] views.py class CategoryListView(ListView): model = Category template_name = 'modules/post/category_detail.html' context_object_name = 'category' queryset = Category.objects.all() def get_queryset(self): queryset = self.queryset.filter(slug=self.kwargs['slug']) return queryset -
template_view error - [Errno 13] Permission denied
PermissionError at /blog/template_view/ [Errno 13] Permission denied: 'C:\DJango\denv\lib\site-packages\django\contrib\admin\templates' Request Method: GET Request URL: http://127.0.0.1:8000/blog/template_view/ Django Version: 3.2.6 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: 'C:\DJango\denv\lib\site-packages\django\contrib\admin\templates' Exception Location: C:\DJango\denv\lib\site-packages\django\template\loaders\filesystem.py, line 23, in get_contents Python Executable: C:\DJango\denv\Scripts\python.exe Python Version: 3.9.1 Python Path: ['C:\DJango\myproject', 'C:\Program Files\Python39\python39.zip', 'C:\Program Files\Python39\DLLs', 'C:\Program Files\Python39\lib', 'C:\Program Files\Python39', 'C:\DJango\denv', 'C:\DJango\denv\lib\site-packages'] Server time: Wed, 18 Aug 2021 02:29:57 +0000 Traceback Switch to copy-and-paste view I am getting this error. please someone help me out -
TemplateDoesNotExist at / template path
I want to create the backend of a portfolio and I'm trying to use a template but it says it doesn't exist but shows the correct file path in the error message. This is my views.py: from django.shortcuts import render from django.http import HttpResponse from django.template import loader def home(request): template = loader.get_template('home.html') return HttpResponse(template.render(request)) And this is my templates setting: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ .... ], }, }, ] The directory structure is: my project my project -init.py -settings.py -urls.py -manage.py -my app templates static -
models.E005 The field 'xxx' from parent model 'x.x' clashes with the field 'xxx' from parent model
Django inheritance error: (models.E005) Do you have a solution to get around this problem, is there a way to add a prefix or idk because I must have several User with the same heritage? Django dont like this: class Dispositif(Infos, ChefGO, ADJChefGO): bcs ChefGO and ADJChefGO depend on the same class Member, but i realy need two member class Members(models.Model): phone_regex = RegexValidator(regex=r'^[0-9]{10}$', message="Error: Format 0611223344") indicative = models.CharField(max_length=16, default="Default indicative") phone = models.CharField(max_length=10, validators=[phone_regex]) class Meta: abstract = True class ChefGO(Members): pass class ADJChefGO(Members): pass class Dispositif(Infos, ChefGO, ADJChefGO): name = models.CharField(max_length=32, default="Name") place = models.CharField(max_length=64) start_date = models.DateTimeField(default=datetime.datetime.now) end_date = models.DateTimeField(default=datetime.datetime.now) Thanks