Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I place images (variable number of them) relatively to each other and also scale jumbotron they are in accordingly? Django
I wanted to ask you for your help. I fought with it for quite a long time but I couldn't come up with good solutions. This is my first project in django and html/css/js so I am sorry in advance :P I created two images that will help me explain my problem: In this case I have three images, pngs with alpha. Actual image is in red "I-1". Darker border is actual image size. By default they of course stack like that. And yellow is other stuff. When I place them ether by position relative or absolute it looks like that: And it is also quite logical why this happens. This is kinda what I want to achieve. But there are two/three problems: 1.1 - Other stuff for website is way down, this looks weird and I don't like that. 1.2 - My jumbotron also is stretched way down. 2 - I have different amount of images in various cases. Sometimes there are 3 of them and sometimes 5 of them. And each one of them I need to place a little bit different. That is a big problem for me. I managed to create three types of them, when … -
Bulk Update Objects in Django Rest Framework
I would like to bulk update some model objects with validation. I am sending a PUT request with the following request body: [{ "id": 1, "is_passed": true }, { "id": 2, "is_passed": true }] My view to handle this request currently looks like: class BulkUpdateAPIView(UpdateAPIView): permission_classes = [AllowAny] serializer_class = BulkUpdateSerializer queryset = Example.objects.filter(is_active=True) def put(self, request, *args, **kwargs): data = self.request.data ids = list() for item in data: ids.append(item['id']) instances = self.queryset.filter(pk__in=ids) serializer = BulkUpdateSerializer(data=data, instance=instances, many=True) serializer.is_valid(raise_exception=True) if serializer.is_valid(): # do something return Response(status=HTTP_200_OK) and the BulkUpdateSerializer looks like: class BulkUpdateSerializer(ModelSerializer): class Meta: model = Example fields = [ 'id', 'is_passed', ] def validate_is_passed(self, value): for item in self.instance: if item.verified_by is not None: raise ValidationError('%s has already been verified.' %(item.name)) I am having several issues here: The put method expects a list in the request body, if a user sends a wrong data type or a wrong format of data how can return an error message mentioning what is wrong with the request? The ValidationError in validate_is_passed is being called twice. Therefore, the same error is returning twice. How can I make sure that it is being called only once? Is it possible to add an update … -
OperationalError at /accounts/login/ attempt to write a readonly database when running a django application with docker
I am running Django application with docker after running docker-compose up all is well but when I try to login in the application as admin I get the following error: OperationalError at /accounts/login/ attempt to write a readonly database What could be the problem? Here are my logs: web_1 | return super().dispatch(request, *args, **kwargs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 88, in dispatch web_1 | return handler(request, *args, **kwargs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/views/generic/edit.py", line 142, in post web_1 | return self.form_valid(form) web_1 | File "/usr/local/lib/python3.7/site-packages/django/contrib/auth/views.py", line 90, in form_valid web_1 | auth_login(self.request, form.get_user()) web_1 | File "/usr/local/lib/python3.7/site-packages/django/contrib/auth/__init__.py", line 108, in login web_1 | request.session.cycle_key() web_1 | File "/usr/local/lib/python3.7/site-packages/django/contrib/sessions/backends/base.py", line 298, in cycle_key web_1 | self.create() web_1 | File "/usr/local/lib/python3.7/site-packages/django/contrib/sessions/backends/db.py", line 55, in create web_1 | self.save(must_create=True) web_1 | File "/usr/local/lib/python3.7/site-packages/django/contrib/sessions/backends/db.py", line 87, in save web_1 | obj.save(force_insert=must_create, force_update=not must_create, using=using) web_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 718, in save web_1 | force_update=force_update, update_fields=update_fields) web_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 748, in save_base web_1 | updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) web_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 831, in _save_table web_1 | result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) web_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 869, in _do_insert web_1 | using=using, raw=raw) web_1 | … -
KeyError: Weird behavior of folium choropleth
I am trying to add choropleth map in Django. As a test, I created a file, say sample.py: All good. import folium import pandas as pd from io import StringIO state_geo = 'https://raw.githubusercontent.com/python-visualization/folium/master/examples/data/world-countries.json' state_unemployment = StringIO(''' State,Unemployment Pakistan,7 Bangladesh,8 India,10 ''') state_data = pd.read_csv(state_unemployment) m = folium.Map() folium.Choropleth( geo_data=state_geo, name='choropleth', data=state_data, columns=['State', 'Unemployment'], key_on='feature.properties.name', fill_color='YlOrRd', fill_opacity=0.7, line_opacity=0.2, nan_fill_color='white', nan_fill_opacity=0, legend_name='Unemployment Rate (%)', ).add_to(m) folium.LayerControl().add_to(m) m.save('choropleth.html') Django But when I try the exact piece of code in views.py, I get below error. I checked that State column does exist in dataframes as well as in geojson views.py def home_test(request): state_geo = 'https://raw.githubusercontent.com/python-visualization/folium/master/examples/data/world-countries.json' state_unemployment = StringIO(''' State,Unemployment Pakistan,7 Bangladesh,8 India,10 ''') state_data = pd.read_csv(state_unemployment) m = folium.Map(location=[48, -102], zoom_start=3, tiles="CartoDB positron") folium.Choropleth( geo_data=state_geo, name='choropleth', data=state_data, columns=['State', 'Unemployment'], key_on='feature.properties.name', # fill_color='BuGn', fill_color='YlOrRd', fill_opacity=0.7, line_opacity=0.2, nan_fill_color='white', nan_fill_opacity=0, legend_name='Unemployment Rate (%)', line_color='red' ).add_to(m) folium.LayerControl().add_to(m) # THE BELOW LINES ARE THE ONLY DIFFERENCE - which shouldn't be the cause of error map_html = m.get_root().render() context = { 'map_html': map_html } return render(request, "index-a.html", context) Any clue as to what am I missing here would be a great help. -
Play youtube audio only from url in django
So I am making a django app in which you can look up a video by a keyword and you get the url back. I want to play the youtube video on my page. I know I can do that with embed code but I want to play only the audio without the video. What is the best way to do that? -
Create a GIF from Video using Django Signals and MoviePy
I wanted to apply Django's Signals to the following model: class Video(models.Model): created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=100, blank=True) image = models.ImageField(upload_to='Images/',blank=True) video = models.FileField(upload_to='Videos/',blank=True) gif = models.FileField(upload_to = 'Videos/', blank = True) class Meta: ordering = ('created', ) The reason why I use signals: Whenever a Video object gets created, we get notified and then we update its gif field using its video field with the help of MoviePy. So, after reading this , I created a signals.py with the following content: # videos/signals.py from moviepy.video.io.VideoFileClip import VideoFileClip from videos.models import Video from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=Video) def create_gif_from_video(sender, instance, created, **kwargs): if created: instance.gif = VideoFileClip(instance.video.name).subclip(0,2).write_gif("myGif.gif") instance.save() Then in videos/apps.py, I did this: from django.apps import AppConfig class VideosConfig(AppConfig): name = 'videos' def ready(self): import videos.signals And in videos/\__init\__.py, I did this: default_app_config = 'videos.apps.VideosConfig' But I get the following error: Internal Server Error: /videos/upload/ Traceback (most recent call last): File "/home/ac3l1k/Desktop/PROJECT/djangoProject/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/ac3l1k/Desktop/PROJECT/djangoProject/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ac3l1k/Desktop/PROJECT/djangoProject/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ac3l1k/Desktop/PROJECT/djangoProject/env/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ac3l1k/Desktop/PROJECT/djangoProject/env/lib/python3.6/site-packages/django/views/generic/base.py", line 71, … -
Deployed Django 3 project doesn't sees static files
Deployed (on server) Django 3 project doesn't sees static and css files(whole static folder), the local on development machine works perfectly. The guide that I have followed is this. I have et up a Digital ocean droplet with ubuntu 18.04 Than all the other staff with Postgres, Nginx, and Gunicorn as in the guide but the static files (image, SVG, css, files doesn't load in) I have my bootstrap CSS files downloaded to local directory The website is online and if I press F12 in chrome it puts out the following error messages (turning DEBUG = True does not deliver any more error messages or error page) Failed to load resource: the server responded with a status of 404 (Not Found) homepage03_comp.png:1 Failed to load resource: the server responded with a status of 404 (Not Found) logo_03c_small.png:1 Failed to load resource: the server responded with a status of 404 (Not Found) jquery.min.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) bootstrap.min.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) popper.min.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) tiktok_col.svg:1 Failed to load … -
Django Queryset same template for different vews
I have two view functions in the view.py def function1(request): qset = Table1.objects.values( 'Field1__code', 'Field2__descr', 'Field3__nr', ... ) return render(request, 'template.html', {'qset':qset}) def function2(request): qset = Table2.objects.values( 'Field4__abc', 'Field5__def', 'Field6__fgh', ... ) return render(request, 'template.html', {'qset':qset}) I want to use the same template.html for both views. How can I send from both functions in the content {'qset':qset} to the template same key names, like "x1", "x2", "x3" (or qset.x1, qset.x2, qset.x3) instead of sending two different sets of keys? The template.html contains keys "x1", "x2", "x3". Thank you -
Django queryset annotate grouping issue
I'm trying to achieve the following query with Django ORM: Select SUM("carros_gasto"."monto"), extract('week' from fecha) as week From carros_gasto group by week so I get the results like this: In django ORM I have tried the following queryset: Gasto.objects.all().annotate(week=ExtractWeek('fecha')).values('week').annotate(Sum('monto')) and I get the restults like this: <QuerySet [{'week': 11, 'monto__sum': Decimal('100.00')}, {'week': 12, 'monto__sum': Decimal('100.00')}, {'week': 12, 'monto__sum': Decimal('300.00')}, {'week': 12, 'monto__sum': Decimal('1200.00')}]> the grouping is not working as expected. This is the query that I see behind curtains in django: SELECT EXTRACT('week' FROM "carros_gasto"."fecha") AS "week", SUM("carros_gasto"."monto") AS "monto__sum" FROM "carros_gasto" GROUP BY EXTRACT('week' FROM "carros_gasto"."fecha"), "carros_gasto"."fecha" ORDER BY "carros_gasto"."fecha" ASC I see that is grouping by week and 'fecha' instead of just the week. Note: I'm using PostgreSQL -
How to return actual file data instead of file URL from Django Rest Framework FileField object
I am trying to build a simple API that returns XML file data to the client. I am using Django 3.0.4 and Django Rest Framework 3.11.0 and have based most of my work on this tutorial https://www.django-rest-framework.org/tutorial/1-serialization/ This is my model: from django.db import models class File(models.Model): file = models.FileField(blank=False, null=False) device = models.CharField(max_length=20, primary_key=True) class Meta: verbose_name_plural = "API" def __str__(self): return self.file.name This is the views: from django.shortcuts import render from rest_framework.parsers import FileUploadParser from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from .serializers import FileSerializer from .models import File class FileList(APIView): """ List all files, or create a new file. """ def post(self, request, format=None): serializer = FileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request, format=None): files = File.objects.all() serializer = FileSerializer(files, many=True) return Response(serializer.data) class FileDetail(APIView): """ Retrieve, update or delete a file instance. """ def get(self, request, pk, format=None): file = File.objects.get(pk=pk) serializer = FileSerializer(file) return Response(serializer.data) This is the App URLs: from django.urls import path from .views import FileList from .views import FileDetail from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('<str:pk>', FileDetail.as_view()), path('', FileList.as_view()), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have … -
buy x get y free drf django
i want to implement buy x get y on product models and only user are listing on order api. models.py: class Product(models.Model): name = models.CharField(max_length=50) price = models.CharField(max_length=10) def __str__(self): return self.name class OrderProduct(models.Model): order_status = ( ('created','created'), ('processing','processing'), ('ordered','ordered') ) user = models.ForeignKey(User,on_delete=models.CASCADE) item = models.ForeignKey(Product,on_delete=models.CASCADE, related_name='products') order_status = models.CharField(choices=order_status,null=True,max_length=50) ordered_date = models.DateTimeField(auto_now_add=True,blank=True,null=True) def __str__(self): return str(self.user) serializers.py: class Product(models.Model): name = models.CharField(max_length=50) price = models.CharField(max_length=10) def __str__(self): return self.name class OrderProduct(models.Model): order_status = ( ('created','created'), ('processing','processing'), ('ordered','ordered') ) user = models.ForeignKey(User,on_delete=models.CASCADE) item = models.ForeignKey(Product,on_delete=models.CASCADE, related_name='products') order_status = models.CharField(choices=order_status,null=True,max_length=50) ordered_date = models.DateTimeField(auto_now_add=True,blank=True,null=True) def __str__(self): return str(self.user) serializers.py: class ProductSerializers(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class OrderProductSerializers(serializers.Serializer): user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) item = ProductSerializers(many=True, read_only=True) class Meta: models = OrderProduct fields = ('item','user','order_status','ordered_date') views.py: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializers class OrderViewSet(viewsets.ModelViewSet): def list(self, request): queryset = OrderProduct.objects.all() serializer = OrderProductSerializers(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = OrderProduct.objects.get(pk=pk) serializer = OrderProductSerializers(queryset) return Response(serializer.data) def create(self,request): data = request.data.get("order") serializer = OrderProductSerializers(data=data,many=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py: path('product/list/',ProductViewSet.as_view({'get':'list'}),name='product_list'), path('product/<pk>/',ProductViewSet.as_view({'get':'retrieve'}),name='product_retrieve'), path('product/',ProductViewSet.as_view({'post':'create'}), name='product_create'), path('order/list/',OrderViewSet.as_view({'get':'list'}),name='order_list'), path('order/<pk>/',OrderViewSet.as_view({'get':'retrieve'}),name='order_retrieve'), path('order/',OrderViewSet.as_view({'post':'create'}), name='order_create') ........................................................................................................................................................................................ -
Handle one Django form in separated HTML forms
I have a web project for uni and I took this as an opportunity to start learning Django. I have a big Django form splitted in the HTML code between several div tags, each div containing a form tag where some of Django's form fields are expanded. My problem is when submitting it. If I have a submit button in a HTML form, I will receive only the Django's form fields from that HTML form. How can I obtain the values of all the form fields? I tried adding one button at the end of all divs but that didn't work either. For example: The first "Next form" button will send me to the second form. If I click the submit button, in the backend I will receive only form.field_three and form.field_four and I would like to receive also form.field_one and form.field_two. Thank you! <div class="example-one"> <form method="POST"> {% csrf_token %} {{form.field_one}} {{form.field_two}} <input type="button" value="Next form"> </form> </div> <div class="example-two"> <form method="POST"> {% csrf_token %} {{form.field_three}} {{form.field_four}} <input type="submit" value="OK"> </form> </div> -
Sending mail in python django
I want to configure a setting to send the mail using python django. But I don't want to use username and password. Is it possible? -
I need a better way to do this
Am having issues doing something. I need a better way of doing it. It is about the get_absolute_url. everything about it is actually working fine but it failed in some part of my template. In the views i have this function def get_category_count(): queryset = Post.objects.values('categories__title').annotate(Count('categories')) return queryset and i used it right here in another function in the view like this def blog(request): category_count = get_category_count() most_recent = Post.objects.order_by('-timestamp')[0:3] context = { 'most_recent': most_recent, 'category_count':category_count } return render(request, 'blog.html', context) And i have actually done a category slug function like this def category(request, slug ): queryset = Post.objects.all() if slug: category_object = get_object_or_404(Category, slug=slug) queryset = queryset.filter(categories__title=category_object) context = { 'queryset':queryset, } return render(request, 'category.html', context) Now in the template of blog i have this <div class="category"> {% for cat in post.categories.all %} <a href="{{cat.get_absolute_url}}">{{ cat.title }}</a> {% endfor %} </div> now it happened that in this same template i have another section where i have this {% for cat in category_count %} <div class="item d-flex justify-content-between"> <a href="{{cat.get_absolute_url}}">{{cat.categories__title }}</a> <span>{{cat.categories__count}}</span> </div> {% endfor %} it happened that right here the get_absolute_url did not work. Maybe because of the get_category_count function in the views. Now i need a better … -
How to check password and show error message in django template?
I want to show error message if user provide the wrong password on logging. Even if I enter wrong password, it shows me Username do not match error. This is my views.py def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(request, username=username, password=password) if user is not None: auth.login(request, user) return redirect('frontend:index') else: if request.user.username != request.POST['username']: messages.error(request, 'Username do not match.') return redirect('accounts:login') elif request.user.password != request.POST['password']: messages.error(request, 'Password do not match') return redirect('accounts:login') else: return render(request, 'accounts/login.html') -
How to use ajax with django pagination in table?
So in my page i have one historic table, i tried paginate that in view like this: paginator = Paginator(historic_approval, 5) # Show 50 per page page = self.request.GET.get('page') try: historic_approval = paginator.page(page) except PageNotAnInteger: historic_approval = paginator.page(1) except EmptyPage: historic_approval = paginator.page(paginator.num_pages) return Response({'list_pending': list_pending, 'historic_approval': historic_approval}) But this way every time i change a page in this table the page is refresh I tried use django el_pagination but not work for me. This my django template: {% if historic_approval %} <div class="col-md-7 col-md-offset-12" style="border-left: 3px solid #337AB7; padding-bottom:20px"> <span class="lead text-muted">{{ internal_title_list_count|default:"" }} {% trans "Meu histórico de aprovações" %} </span> <div style="border: 1px dashed #337AB7; background-color:#F4FAFF; padding:20px 10px;margin-top:10px"> {% paginate historic_approval %} {% for requisition in historic_approval %} <div class="row" style="border: 1px dashed #ddd; background-color:#fff; padding:10px; margin:10px 0;"> <div class="col-xs-12"> {{ requisition.requisition }}</br> <small class="alert-success"> {% trans 'Aprovada em' %}: {{ requisition.date_approved }}</small> </div> </div> {% endfor %} {% show_pages %} </div> </div><!-- end col --> {% endif %} </div><!-- end row --> -
Getting AttributeError when 'authenticate' in custom AuthenticationForm
I am trying to customize the default AuthenticationForm for some of my requirements in Django. Customized login works good when I am enter correct credentials. But if I enter incorrect password, then I am getting error message as below. error message (or exception) raised while authenticating at code "self.user_cache = authenticate(username=username, password=password)". Please help me if I am missing anything here. Error AttributeError at /login/ 'CustomAuthenticationForm' object has no attribute 'authenticate' Request Method: POST Request URL: http://127.0.0.1:8000/login/?next=/ Django Version: 1.6.10 Exception Type: AttributeError Exception Value: 'CustomAuthenticationForm' object has no attribute 'authenticate' Exception Location: C:\vmshare\workspace\DAU_2\dau_gui\venv\lib\site-packages\django\contrib\auth\__init__.py in authenticate, line 49 Python Executable: C:\vmshare\workspace\DAU_2\dau_gui\venv\Scripts\python.exe Python Version: 2.7.9 My customized login class CustomAuthenticationForm(AuthenticationForm): def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username is not None and password: try: user = User.objects.get(username=username) except User.DoesNotExist: user = None raise forms.ValidationError('User does not exist.') try: self.user_cache = authenticate(username=username, password=password) except User.DoesNotExist: raise forms.ValidationError('Incorrect password.') if user is not None: self.confirm_login_allowed(user) else: raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name},) return self.cleaned_data def confirm_login_allowed(self, user): if not user.is_active: raise forms.ValidationError('There was a problem with your login.', code='invalid_login') In my settings.py I added this AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend','dau_gui_app.forms.CustomAuthenticationForm') -
Django - passing arguments between views
I want to pass the argument "x" from the first view to the second one for further processing but I always fail with the error: ['“$input_of_x” is not a valid UUID.'] (my user object is a UUID) I don't understand how to make those two views talk with each other, maybe somebody can explain to me how i can make x reachable in def execute(request) function. def check(request) user = request.user form = UserInputX(data=request.POST) if form.is_valid(): x = str(form.data.get("input")) check_x = \ ... if check_x == str('true'): if blabla: request.session['userID'] = x return redirect(reverse('execute')) else: messages.error(request, 'some error text output') return redirect('check') ... def execute(request): user = User.objects.get(id=request.session['userID']) form = Y_Form(request.POST) if request.method == "POST": if form.is_valid(): if request.POST['y'] == user.y: ... user.save() messages.success(request, 'some success message') return redirect('check') ... else: return redirect('execute') -
Debug Docker Container with Visual Studio Code
I have a Django project in Visual Studio Code. I start it through a virtual machine (linux) using Docker. I want to be able to debug the project by adding breakpoints. I tried following this tutorial, but can't get it: https://code.visualstudio.com/docs/containers/debug-python The application starts in "localhost: 8000", the private IP of the physical machine is 192.168.0.102 and that of the virtual machine: 192.168.56.1. My file launch.json: { "name": "Python: Remote Attach", "type": "python", "request": "attach", "port": 5678, "host": "192.168.56.1", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/code" } ] } My views.py: # -*- coding: utf-8 -*- import tempfile, time import json import ptvsd ptvsd.enable_attach(address=('192.168.56.1', 5678)) #This is ok? ptvsd.wait_for_attach() ... The error: csuperior-web | Performing system checks... csuperior-web | csuperior-web | Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f4742165b70> csuperior-web | Traceback (most recent call last): csuperior-web | File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper csuperior-web | fn(*args, **kwargs) csuperior-web | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run csuperior-web | self.check(display_num_errors=True) csuperior-web | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check csuperior-web | include_deployment_checks=include_deployment_checks, csuperior-web | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks csuperior-web | return checks.run_checks(**kwargs) csuperior-web | File "/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks csuperior-web | new_errors = check(app_configs=app_configs) csuperior-web | File … -
Overriding from_db() in django models gives NoneType object has no attribute _meta
I've been tampering with django from_db() class method, Here's what I have class URL(models.Model): full_version = models.URLField() short_version_extension = models.CharField(unique=True, blank=True, max_length=10) expiration_time = models.TimeField() class Meta: verbose_name = 'Link' @classmethod def from_db(cls, db, field_names, values): super(URL, cls).from_db(db, field_names, values) This should be a URL shortener. I'm trying to save only the extension of the generated URL instead of saving it as whole (as the site is the same in all of them), I want to override from_db() to always add the short_version_extension to the current website (the one the django project is uploaded to). here's an example. www.mydomain.com\extension\ I want to save only the extension, and when I get it from the db, I want to add the www.mydomain.com. When I tried to override from_db(), I called super(URL, cls).from_db(db, field_names, values) to check if everything is working. But it didn't work as shown in image.1 I've tried to solve it by copying the body of from_db() from django code base, like this @classmethod def from_db(cls, db, field_names, values): if len(values) != len(cls._meta.concrete_fields): values_iter = iter(values) values = [ next(values_iter) if f.attname in field_names else DEFERRED for f in cls._meta.concrete_fields ] new = cls(*values) new._state.adding = False new._state.db = db … -
How to log using django background tasks?
I can easily create logs throughout the application using the logging module, but inside a django background task it does not work. import logging from background_task import background log = logging.getLogger("django") @background(schedule=1) def do_something(): log.info("it worked") running do_something() does not log anything, but if I remove the decorator it works... Does anyone know how to make it work? -
Setting an image rendition to center crop in Wagtail
I'm working on a CMS build (Python, Django, Graphene, Wagtail). I know wagtail offers a get_rendition that can resize an image to fit given dimensions (Similar to CSS background-size: cover). The options that appear to be available are based on resizing: https://docs.wagtail.io/en/v1.3.1/topics/images/using_in_templates.html#image-tag-alt But I'm looking for just a center crop with no resizing. -
Django python Javascript change url and call views without reloading
I am creating a new Django python project. I have an html that calls on a jquery to show a chart (using chart js) My views is: def CellsHistories(request,Cell_id): CellData = cellData.cell_Data(Cell_id) context = { 'CellData':CellData, } return render(request,'Main/index.html',context) calling that from url as: urlpatterns = [ path('CellsHistories/<int:Cell_id>/',views.CellsHistories), ] and the js for the chart has an onclick function that is: onClick: function(e) { var element = this.getElementAtEvent(e); // this is the charts object in this case and element becomes the clocked bubble if (element.length > 0) { var datasetLabel = this.config.data.datasets[element[0]._datasetIndex].label; var data = this.config.data.datasets[element[0]._datasetIndex].data[element[0]._index]; } var url = window.location.href url = url.replace(/\/[^\/]*[\/]$/, '/'+element[0]._datasetIndex+'/') window.location.replace(url); document.getElementById('SelectedCellbadge').textContent = 'Cell No. ' + element[0]._datasetIndex; } That works fine. My problem is that everytime that the url changes and the views is called the page reloads at the top. I have tried the pushstate() function which changes the url but does not call the views function again (django views called through my url request). Can I please have some ideas on how to change the url and trigger the django urls, and then views but without the page going to the top? I just want to be able to use my onclick … -
Type mismatch in django serializer for request parsing
I had created the following serializers for request parsing of JSON data. However, while performing the operation, I get an unexpected error. class A(serializers.ModelSerializer): class Meta: model = CName fields = ('id','contact','email') read_only_fields=('contact',) class B(serializers.ModelSerializer): class Meta: model = PName fields = ('id','contact','number') read_only_fields=('contact',) class C(serializers.ModelSerializer): contact_number = A(many=True) contact_email = B(many=True) class Meta: model = Contact fields = ('id','name','contact_number','contact_email') def create(self,validated_data): contact_number=validated_data.pop('contact_number') contact_email =validated_data.pop('contact_email') instance = Contact.objects.create(**validated_data) for number in contact_number: PName.objects.create(contact=instance,**number) for email in contact_email: CName.objects.create(contact=instance,**email) return instance def update(self, instance, validated_data): contact_number=validated_data.pop('contact_number') contact_email =validated_data.pop('contact_name') Contact.objects.filter(id=instance.id).update(**validated_data) number_to_keep=[] email_to_keep=[] for number in contact_number: if number.get('id'): ph_id = number.pop('id') PName.objects.filter(id=ph_id).update(**number) number_to_keep.append(ph_id) else: ph=PName.objects.create(contact=instance,**number) number_to_keep.append(ph.id) for email in contact_email: if email.get('id'): em_id = email.pop('id') CName.objects.filter(id=em_id).update(**email) email_to_keep.append(em_id) else: em = CName.objects.create(contact=instance,**email) email_to_keep.append(em.id) instance.contact_number.exclude(id__in=number_to_keep).delete() instance.contact_email.exclude(id__in=email_to_keep).delete() return instance I have a json-format where I am passing the request data in the format: { "contact_number": "9999999999", "contact_email":"timsh@hotmail.com" } While calling up the serializer using the following code: contact_details = Contact.objects.get(rest = rest) contact_serializer = ContactSerializer(contact_details,data=request.data) I received the response as below: { "contact_number": { "non_field_errors": [ "Expected a list of items but got type \"unicode\"." ] }, "contact_email": { "non_field_errors": [ "Expected a list of items but got type \"unicode\"." ] } } Note: I … -
Template not file Found Django
I am trying to make a home page of a new website via django. My app name is 'blog', home page is home.html I still receive the error 404 when I go to http://127.0.0.1:8000/blog/home.html I made sure I added 'blog' to my templates in settings.py and that I added the folder templates in the main directory as well as through blog/templates/blog/home.html blog/views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'blog/home.html') blog/urls.py from django.urls import path from . import views urlpatterns = [ path('home/', views.home, name='home'), ] myproject/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], myproject/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), ] Do you see anything in my code which cause problem? I receive the message in blog/views.py that "Template file 'blog' not found" on the line return render(request, 'blog/home.html')