Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Override django-ckeditor bullet style class
I have a django application that I'm using with tailwind, and I'd like to be able to apply the tailwind classes to my bullet lists by default. I have tried adding a custom style in the config.js file as well as the styles.js file, but for some reason it doesn't seem to update with any changes I make there? I've tried running collect static but it says files are unmodified 0 static files copied to '/code/myproject/static', 1280 unmodified. config.js CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.format_p={element:"p", name: "Normal", styles:{ 'color': 'red'}}; }; styles.js CKEDITOR.stylesSet.add( 'default', [ ] ); I don't have the bullet styles there yet, but even the paragraph change is not picking up. I realise I can do this with javascript to add class to all ul and li elements, but I'd rather not do that if there's a cleaner solution. -
Understanding Django exclude queryset on ForeignKey relationship
Really struggling to explain this one. I have the following models class Star(models.Model): name = models.CharField(max_length=200, blank=False) slug = models.SlugField(max_length=255, unique=True) class Image(models.Model): star = models.ForeignKey(Star, on_delete=models.CASCADE, related_name='images') status = models.BooleanField(verbose_name="Show online", default=True) With the following data Star table star name slug 1 Star 1 star-1 2 Star 2 star-2 Image table star status 1 False 1 True 2 True 2 False I then have the following query to grab a single star object with all the associated images with a status of True. star = Star.objects.filter(slug=slug).exclude(images__status=False).get() However this retunrs DoesNotExist exception, despite images with a status of true existing. Can anybody explain this? Any help would be much appreciated. -
construct url dynamically (name view as argument) with name space url tag in Django template
In a Django template, I want to construct dynamically urls I try to concatenate (see below) but got an error : Could not parse the remainder: '+key+'_index'' from ''ecrf:'+key+'_index'' {% for key, values in forms.items %} <!-- for exemple a key would be 'inclusion' --> <a href="{% url 'ecrf:'+key+'_create' %}">{{ key|capfirst }}</a> {% endfor %} urls app_name='ecrf' urlpatterns = [ path('inclusion/create/', views.InclusionCreate.as_view(), name='inclusion_create'), expected result: <a href="/localhost/ecrf/inclusion">Inclusion</a> -
Django - generate Zip file and serve (in memory)
I'm trying to serve a zip file that contains Django objects images. The problem is that even if it returns the Zip file, it is corrupted. NOTE: I can't use absolute paths to files since I use remote storage. model method that should generate in memory zip def generate_images_zip(self) -> bytes: content = BytesIO() zipObj = ZipFile(content, 'w') for image_fieldname in self.images_fieldnames(): image = getattr(self, image_fieldname) if image: zipObj.writestr(image.name, image.read()) return content.getvalue() ViewSet action @action(methods=['get'], detail=True, url_path='download-images') def download_images(self, request, pk=None) -> HttpResponse: product = self.get_object() zipfile = product.generate_images_zip() response = HttpResponse(zipfile, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=images.zip' return response When I try to open the downloaded Zip file, it says it's corrupted. Do you know how to make it work? -
How can I make one out of two fields required in my model/serializer?
I'm trying to allow my user to input either their email or their phone to continue. I've read a bunch of answers on here but none of them seem to work. For now I have the constraint in my model by it just returns " NOT NULL constraint failed: core_client.phone " This is the model and the serializer: class Client(models.Model): email = models.EmailField(max_length=200, unique=True, blank=True) phone = models.IntegerField(unique=True, blank=True) def clean(self): super(Client, self).clean() if self.email is None and self.phone is None: raise ValidationError('Validation error text') return super(Client, self).clean() def __str__(self): return self.email class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = '__all__' Is there a better way to do it? I only want to the user to be created if both fields are filled but the user should still be able to continue on the website if they only wrote either one of the fields (there just wouldn't be an account for that user since they only completed one field). -
Django. Moving a redis query outside of a view. Making the query results available to all views
My Django app has read-only "dashboard" views of data in a Pandas DataFrame. The DataFrame is built from a redis database query. Code snippet below: # Part 1. Get values from the redis database and load them into a DataFrame. r = redis.StrictRedis(**redisconfig) keys = r.keys(pattern="*") keys.sort() values = r.mget(keys) values = [x for x in vals if x != None] redisDataFrame = pd.DataFrame(map(json.loads, vals)) # Part 2. Manipulate the DataFrame for display myViewData = redisDataFrame #Manipulation of myViewData #Exact steps vary based from one view to the next. fig = myViewData.plot() The code for part 1 (query redis) is inside every single view that displays that data. And the views have an update interval of 1 second. If I have 20 users viewing dashboards, the redis database is getting queried 20 times a second. Because the query sometimes takes several seconds, Django spawns multiple threads, many of which hang and slow down the whole system. I want to put part 1 (querying the redis database) into its own codeblock. Django will query redis (and make the redisDataFrame object) once per second. Each view will copy redisDataFrame into its own object, but it won't query the redis database over and … -
Make history for someting
i need to make tickets for an equipment How to filter that in views.py class Filter_Tickets(LoginRequiredMixin, ListView): model = Ticket template_name = 'workflow/history_of_equipment.html' def queryset(self): if(self.request.user.type == 'ENGINEER'): eng = Engineer.objects.get(id = self.request.user.id) eng_hos = eng.current_hospital dep_list = eng_hos.department_set.all() # ordering by the newest id object_list = [ticket for q1 in dep_list for eq in q1.equipment_set.all() for ticket in eq.ticket_set.all().order_by('-id')] return object_list elif(self.request.user.type == 'DOCTOR'): doc = Doctor.objects.get(id = self.request.user.id) doc_hos = doc.current_hospital dep_list = doc_hos.department_set.all() object_list = [ticket for q1 in dep_list for eq in q1.equipment_set.all() for ticket in eq.ticket_set.all().order_by('-id')] return object_list else: man = Manager.objects.get(id = self.request.user.id) dep_list = man.hospital.department_set.all() object_list = [ticket for q1 in dep_list for eq in q1.equipment_set.all() for ticket in eq.ticket_set.all().order_by('-id')] return object_list def get_context_data(self, **kwargs): context = super(Filter_Tickets, self).get_context_data(**kwargs) if(self.request.user.type == 'ENGINEER'): eng = Engineer.objects.get(id = self.request.user.id) context['eng'] = eng return context -
How to embad (show map in website) GIS shape file data in to my website?
Here, I'm trying to show GIS map in to my website. I'm using GIS dataset from https://opendatanepal.com/dataset/nepal-municipalities-wise-geographic-data-shp-geojson-topojson-kml this site. and I have following files in this dataset: local_unit.dbf local_unit.xml local_unit.shx local_unit.prj local_unit.sbn local_unit.sbx local_unit.shp Now I have problem is to use this file in to my Django/Python website. I'm trying to use like jquery library with ArcGIS from this: https://developers.arcgis.com/javascript/3/jssamples/framework_jquery.html. I don't know this is good way or not t use. Please suggest me how can I use GIS map in website. -
Django CSRF exception after removing clickjacking middleware
I need to fully load my website inside an iframe, so I deleted clickjacking middleware but after that, I got 403 code status and CSRF exception, how I can fix this to allow load my website inside iframe? -
Django - Class based view - Meta tags from model don't get passed to template
I am having an issue with my meta tags not being passed to my category.html template. Here are my models.py class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255) image = models.ImageField(null=True, blank=True, upload_to='images/') meta_title = models.CharField(max_length=255) meta_keywords = models.CharField(max_length=255) meta_description = models.CharField(max_length=255) def __str__(self): return self.name Here are my views.py class CategoryView(ListView): model = Post template_name = 'category.html' def get_queryset(self): self.category = get_object_or_404(Category, slug=self.kwargs['slug']) return Post.objects.filter(category=self.category) # def get_context_data(self, **kwargs): # context = super(CategoryView, self).get_context_data(**kwargs) # context['category'] = self.category # return context def get_context_data(self, *args, **kwargs): category_menu = Category.objects.values_list('slug', flat=True) context = super(CategoryView, self).get_context_data(*args, **kwargs) context['category_menu'] = category_menu return context The commented-out code works, however, I need the second one so that I can also display categories (name from Category model) on nav template. Here is my nav template <div class="container-fluid categories-main"> <ul class="categories list-inline mx-auto text-center"> {% for item in category_menu %}<a href="{% url 'categories' item %}">{{ item|capfirst }} {% endfor %}</a> </ul> </div> Here is my url.py urlpatterns = [ path('', HomeView.as_view(), name="home"), path('article/<slug:slug>', ArticleDetailView.as_view(), name="article-detail"), path('category/<slug:slug>', CategoryView.as_view(), name="categories"), and finally here is my category.html {% extends 'base.html' %} {% block title %} {{ category.meta_title }} {% endblock %} {% block meta_extend %} <meta name="description" content="{{ category.meta_description }}"> … -
Create an already populated dashboard with a displayed graph in Atoti using Django
I'm not sure how to word this differently but I'm integrating Atoti with a Django project using their project template, I've searched a lot in their documentation but I can't seem to get an answer about this. What I need to do is after a button click on a Django view, redirect the user to a custom Atoti Dashboard that's already populated with a specific information already displayed (for example, a line graph with a title). I don't need to save it unless the user wants because we're planning on using Atoti mainly as means of visualization. At this point in time, I can only redirect the user to the standard Atoti dashboard with my information and then create what I need to display but that's not user friendly at all and presumes the user has knowledge with Atoti. Anyone know if this is possible and if isn't, anyone has any suggestions on good Data Visualization libraries that make use of Django? Thanks in advance. -
Display the image in the django-tables2
settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' models.py class Product(models.Model): name = models.CharField(max_length=250) image = models.ImageField() tables.py import django_tables2 as tables from .models import Product class ProductTable(tables.Table): class Meta: model = Product fields = ("image" ,"name") views.py In the views.py , I filter the model objects and get QuerySet import django_tables2 as tables from .models import Product from .tables import ProductTable ----- table = ProductTable(new_objects) #new_objects is Product QuerySet return render(request, 'home.html', {'table': table }) Outcome I got a table, but instead of images, only links. How can I display the image? -
Add prices to total with checkbox select Django
i am building a feature to add different services to the checkout in my django template, but i don't know how to add the total price when selecting checkboxes. I put a change event on each checkbox and to this and when i check one it is supposed to add the service and its price in the card. The card : <div class="col-4"> <h4 class="d-flex justify-content-between align-items-center mb-3"> <span class="text-muted">Votre commande</span> </h4> <ul class="list-group mb-3" id="panier"> <li class="list-group-item d-flex justify-content-between lh-condensed"> <div> <h6 class="my-0">{{annonce.titre_logement}}</h6> <small class="text-muted">{{annonce.categorie_logement}}</small> </div> <span class="text-muted">{{annonce.loyer_tc}} €</span> </li> </ul> <li class="list-group-item d-flex justify-content-between"> <span>Total (€)</span> <strong><span id="total"></span> €</strong> </li> </div> The checkboxes and the script : {% for categorie in categorie_service %} {% for service in services %} {% if service.categorie.value == categorie_service.nom %} <div class="form-check"> <input class="form-check-input" type="checkbox" name="service" value="{{ service.nom }}" id="service{{ service.id }}"> <label class="form-check-label" for="service{{ service.id }}"> {{ service.nom }} </label> </div> <script> $(document).ready(function() { $('#service{{ service.id }}').change(function() { if(this.checked) { var returnVal = "<li class='list-group-item d-flex justify-content-between lh-condensed'>\ <div>\ <h6 class='my-0'>{{service.nom}}</h6>\ </div>\ <span class='text-muted'>{{service.price}}€</span>\ </li>" $('#panier').append(returnVal); var total total = {{annonce.loyer_tc}} total = total + parseInt({{service.price}} || 0,10); totalDiv = document.getElementById("total"); totalDiv.innerHTML = total; } }); }); </script> {% endif %} {% … -
Django request.user not showing correct user in frontend
When user updates profile with username which is already in use ,message appear of "A user with that username already exists." but username on profile is changed to which user requested. for example: if user with username test001 update profile with already taken username "test0012" this will happen: Notice:username is updated with "test0012" Code in frontend for username: <h2 id="user-name" class="account-heading user__name">@{{ user.username }}</h2> also going on "my posts" will redirect to posts of user "test0012". code for profile and update: @login_required def profile(request): if request.method=="POST": u_form=UserUpdateForm(request.POST,instance=request.user)#,op_email=request.user.email) p_form=ProfileUpdateForm(request.POST,request.FILES,instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request,f'Your Account has been updated!') #changing email on profile tusername=u_form.cleaned_data.get('username') temail=u_form.cleaned_data.get('email') registeruser=User.objects.get(username=tusername) registeruser.email=temail registeruser.save() return redirect('profile') else: u_form=UserUpdateForm(instance=request.user) p_form=ProfileUpdateForm(instance=request.user.profile) userupdateform code: class UserUpdateForm(forms.ModelForm): email=forms.EmailField() username=forms.CharField(required=True,validators=[username_check,]) class Meta: model =User fields =['username','email'] ProfileUpdateForm: class ProfileUpdateForm(forms.ModelForm): class Meta: model=Profile fields=['image'] -
CSS is not rendering with HTML file in Django
I've been trying to link up my css with the HTML code, but CSS is not working in DJANGO! I'm sharing all the screenshots of my code! Hope anyone can help me out with this. Thanks in advance! h2{ color: blue; } .heading { color: blue; } <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]> <html class="no-js"> <!--<![endif]--> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>MY PROFILE</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> {% load static %} <link rel="stylesheet" href="{% static 'css/index.css' %}"> </head> <body> WELCOME HERE! <h2 class="heading">This is CSS</h2> <script src="" async defer></script> </body> </html> -
GraphQL works on Postman, but not on React - using Django API
When I try to query my API on React, I am getting a 400 Bad Request, however I am able to make the same queries fine on Postman (browser and interface version). I don't get any error message so it seems impossible to troubleshoot. Does anyone know how I can at least troubleshoot this? index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { Route, BrowserRouter as Router, Switch } from 'react-router-dom'; import { ApolloClient, InMemoryCache, ApolloProvider, HttpLink, from } from "@apollo/client"; import { onError } from '@apollo/client/link/error'; const errorLink = onError(({ graphqlErrors, networkError }) => { if (graphqlErrors) { graphqlErrors.map(({ message, location, path }) => { alert(`Graphql error ${message}`); }); } }); const link = from([ errorLink, new HttpLink({ credentials: 'same-origin', uri: "http://localhost:8000/graphql/", fetchOptions: { mode: 'no-cors', }, }), ]); const client = new ApolloClient({ cache: new InMemoryCache(), link: link, connectToDevTools: true, }); ReactDOM.render( <ApolloProvider client={client}> <Router> <React.StrictMode> <Switch> <Route exact path="/" component={App} /> </Switch> </React.StrictMode> </Router> </ApolloProvider>, document.getElementById('root')); Queries.js import { gql } from '@apollo/client' export const LOAD_USERS = gql` query { users { edges { node { email } } } } `; GetUsers.js import React, { useEffect } from 'react'; import … -
Displaying HTML carrots without it being treated as HTML with DJango
I am working with a Django project and right now I am building my HTML table inside of my view and this displaying it on my html template. Some of the data that is in my table looks like <word>. The issue is when it gets displayed it is treating those carrots as HTML code and this the word is not being displayed. I am displaying my table like: {% autoescape off %} {{table}} {% endautoescape %} Any way to make sure the carrots get displayed correctly? -
Django-React deployed app how to go to admin app
i have a web app running on django api on the backend and React on the frontend, after deploying it to heroku everything is working great except i don't know how to go to the admin page since i used to access localy (before deployment) it via 127.0.0.1:8000/admin/ while the main page was running on localhost:3000/ -
ModuleNotFoundError: No module named 'allauth.accounts'
I need to to render two login and signup form on the same page and i use allauth package to do the process,i have already installed djano-allauth and added it to INSTALLED_APS ,this is my code: from allauth.accounts.views import SignupView from allauth.accounts.forms import LoginForm class CustomSignupView(SignupView): # here we add some context to the already existing context def get_context_data(self, **kwargs): # we get context data from original view context = super(CustomSignupView, self).get_context_data(**kwargs) context['login_form'] = LoginForm() # add form to context return context but i get this error : ModuleNotFoundError: No module named 'allauth.accounts' i don't know why i get this error while i have installed the django-allauth package! -
Why js doesn't save in html some information
I am working with django and I am using js and Maps JavaScript API in my web. So, in JS I am saving two values: document.getElementById(id_latitude).value = latitude; document.getElementById(id_longitude).value=longitude; However, the previus lines doesn't save values in the first POST, but yes in the second. I don't know why. Thank you -
Call my Search results view with valid parameters from search
I have a function which puts up a search template and when the search template is completed and valid, calls my search results view which generates the result based on the completed parameters in the response. My problem is I used render to put up the search results page, and the URL does not change (ie. the URL still says get_search, instead of search_results..). It means that the pagination won't work because it doesn't have the correct URL. What should I use to pass the response to the search results view and change the URL. Attempted reverse_lazy but as I expected it gave me an attribute error - 'proxy' object has no attribute 'get'. My function is below: def get_search(request): if request.method == 'POST': form = SearchForm(request.POST) request.method = "GET" request.GET = request.POST if form.is_valid(): return SearchResultsView.as_view()(request) else: form = SearchForm() if form.is_valid(): return SearchResultsView.as_view()(request) else: form = SearchForm(request.GET) return render(request, 'get_search.html', {'form':form}) The search Results view is pretty lengthy but the beginning of the search_results view looks like this: class SearchResultsView(ListView): model = Program template_name = 'search_results.html' paginate_by = 5 def get_context_data(self, **kwargs): context = super(SearchResultsView, self).get_context_data(**kwargs) # segment_results = None program_results = None segment_program_list = None query = … -
Base 64 encoded in python2.7 and decoding in python3.6
Facing issue when base64 decoding in python3.6 whatever encoded in python2.7. Python 2.7: Below is the code, using for encoding. encoded_session = base64.b64encode('{}:{}'.format(_hash,session_str).encode('ascii')).decode('ascii') Let's assume I have some value for _hash and session_str. Python 3.6: I have the encoded_session already and below is what I am trying to decode. _hash, session_str = base64.b64decode(encoded_session).split(b':', 1) when I am executing this, getting the below error. binascii.Error: Incorrect padding I have tried multiple things adding b'==' in encoded_session and other stuff but nothing helps. Please help. -
Only return users that are not already part of a Patient relationship
In my current implementation I can query for users by name. I would like however that the search results only contain users that do not appear as part of a Patient relationship for a certain therapist. Should I try to populate my user objects with their therapist? Or is there a way to filter users out that appear in Patient table with a certain therapist? class User(AbstractUser): is_therapist = models.BooleanField(default=False) is_patient = models.BooleanField(default=True) def __str__(self): return self.email class Patient(models.Model): therapist = models.ForeignKey(User, related_name="patients", on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) complaints = models.TextField(blank=True, default="") class Meta: constraints = [ models.UniqueConstraint(name='unique_patient', fields=['therapist', 'user']) ] class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer def get_queryset(self): queryset = User.objects.all() full_name = self.request.query_params.get('full_name', None) therapist_id = self.request.query_params.get('therapist_id', None) if full_name is not None: queryset = User.objects.annotate(full_name=Concat('first_name', V(' '), 'last_name')).filter(full_name__icontains=full_name) return queryset -
django.db.utils.IntegrityError: null value in column "extra" of relation "units_unit" violates not-null constraint
I'm getting a strange error that I can't find information for. The error occurs for app 'units' on my site deployed on Heroku; it doesn't happen locally. It is as if Django has created a table column that I'm not allowed to access? models.py: class Unit(models.Model): div_number = models.CharField(max_length=200, null=True) div_type = models.CharField(max_length=200, default=None, blank=True, null=True) unit_hierarchy = models.CharField(max_length=200, null=True) nationality = models.CharField(max_length=200, null=True) To demonstrate the error, I'll try to create an instance: >>> from units.models import Unit >>> x=Unit(div_number='1st',div_type='Infantry',unit_hierarchy='Division',nationality='Canada') >>> x <Unit: Canada 1st Infantry Division> But then x.save() gives the following error traceback. >>> x.save() Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.NotNullViolation: null value in column "extra" of relation "units_unit" violates not-null constraint DETAIL: Failing row contains (118, 1st, Infantry, Division, Canada, null). The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/base.py", line 763, in save_base updated = self._save_table( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/base.py", line 906, in _do_insert return manager._insert( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method … -
Django read passwords without bcrypt$
I am using a legacy database that stores passwords for a different application, I have integrated django with it and I found that django reads the password if it has this prefix bcrypt$ django validates this one bcrypt$$2a$10$Pdg3h8AVZ6Vl3X1mMKgQDuMriv8iysnValEa5YZO3j9pEboLrOBUK the app is storing this way $2a$10$Pdg3h8AVZ6Vl3X1mMKgQDuMriv8iysnValEa5YZO3j9pEboLrOBUK settings.py PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.BCryptPasswordHasher', ]