Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'router'
Hi i am getting this error please help me. i am new on this field and i am getting this error. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'first', ] my views.py from django.shortcuts import render from rest_framework.viewsets import ModelViewSet from .serializers import MovieSerializer,RatingSerializers from .models import Movie,Rating # Create your views here. class MovieViewSet(ModelViewSet): queryset=Movie.objects.all() serializer_class=(MovieSerializer,) class RatingViewSet(ModelViewSet): queryset=Rating.objects.all() serializer_class=(RatingSerializers,) my main urls.py is """rest_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('my_apis',include('first.urls')), ] and serializers.py from rest_framework import serializers from .models import Movie,Rating class MovieSerializer(serializers.ModelSerializer): class Meta: model= Movie fields=['title','description'] class RatingSerializers(serializers.ModelSerializer): class meta: model=Rating fields='__all__' models.py is from django.db import models from django.contrib.auth.models import User from django.core.validators import MinValueValidator,MaxValueValidator # Create … -
How to redirect logger django_structlog.middlewares.request to another file?
I use structlog with Django but I found my flat_line.log file difficult to read because every time an action is performed in the admin section there are several new entries like these: timestamp='2020-04-23T15:17:49.196600Z' level='info' event='request_started' logger='django_structlog.middlewares.request' request_id='bf82598e-5a34-4bd0-a698-7556bf4733a4' user_id=1 ip='127.0.0.1' request=<WSGIRequest: GET '/admin/myapp/market/'> user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36' timestamp='2020-04-23T15:17:49.325273Z' level='info' event='request_finished' logger='django_structlog.middlewares.request' request_id='bf82598e-5a34-4bd0-a698-7556bf4733a4' user_id=1 ip='127.0.0.1' code=200 request=<WSGIRequest: GET '/admin/myapp/market/'> timestamp='2020-04-23T15:17:49.465507Z' level='info' event='request_started' logger='django_structlog.middlewares.request' request_id='9e7558a8-2d8f-4145-8569-9c6a74b0090b' user_id=1 ip='127.0.0.1' request=<WSGIRequest: GET '/admin/jsi18n/'> user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36' timestamp='2020-04-23T15:17:49.468317Z' level='info' event='request_finished' logger='django_structlog.middlewares.request' request_id='9e7558a8-2d8f-4145-8569-9c6a74b0090b' user_id=1 ip='127.0.0.1' code=200 request=<WSGIRequest: GET '/admin/jsi18n/'> How can I redirect all entries from logger django_structlog.middlewares.request to another file so they don't flood the log files with a ton of undesired informations? This is how my configuration looks like: LOGGING = { "version": 1, "disable_existing_loggers": True, "formatters": { "json_formatter": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.processors.JSONRenderer(), }, "plain_console": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.dev.ConsoleRenderer(), }, "key_value": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.processors.KeyValueRenderer(key_order=['timestamp', 'level', 'event', 'logger']), }, }, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "plain_console", }, "json_file": { "class": "logging.handlers.WatchedFileHandler", "filename": "json.log", "formatter": "json_formatter", }, "flat_line_file": { "class": "logging.handlers.WatchedFileHandler", "filename": "flat_line.log", "formatter": "key_value", }, }, "loggers": { '': { "handlers": ["console", "flat_line_file", "json_file"], "level": "INFO", } } … -
How to change header/page title of change list page in Django Admin
I'm working on Django.And I wanted to change the header in the change list page in the Django admin as marked with red color in the pic and my admin.py file looks like this: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): change_form_template = 'change_form.html' add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So my question is how to change the header in the change list page as shown in the pic?? Thanks in advance!! -
Django: CSRF verification fails despite token is provided
In my template I have an "edit" button which toggles hidden row and sends an ajax call to the server in order to render an appropriate edit form there. When I try to submit a form I get 403 error due to CSRF token is missing or incorrect despite it is provided in form. Here is my HTML for table contents: {% for cleaning in cleaning_list %} <tr> <td id="td-name{{cleaning.id}}" class="text-md-center">{{ cleaning.name }}</td> <td id="td-difficulty{{cleaning.id}}" class="text-md-center">{{ cleaning.difficulty }}</td> <td id="td-frequency{{cleaning.id}}" class="text-md-center">{{ cleaning.frequency }}</td> <td class="text-md-center"> <button id="edit_btn{{cleaning.id}}" type="button" class="btn btn-warning btn-sm update-cleaning" name="show" value="{{cleaning.id}}">Edit</button> </td> </tr> <tr id='tr-{{cleaning.id}}' style="display: none"> {% include "cleaning_update.html" %} </tr> {% empty %} <tr> <td colspan="7" class="text-center bg-warning">There is no cleaning here yet :( Add some faster </td> </tr> {% endfor %} Here is a "cleaning_update" html: <form id="cleaning-save-update-form{{scleaning.id}}" method="post" action="{% url 'ajax_update_cleaning' %}"> {% csrf_token %} {% for field in form %} <td class="text-md-center"> {{field.label}}: {{ field }} </td> {% endfor %} <td class="text-md-center"><input id="{{scleaning.id}}" class="btn btn-primary save-updates-cleaning" type="submit" value="Change"></td> </form> Here is my js: $(function () { $(document).on('click', '.update-cleaning', function(event) { var target_id = $(this).attr('value') var btn_name = $(this).attr('name') $.ajax({ url: "{% url 'ajax_update_cleaning' %}", type: 'get', data: {'id': target_id}, dataType: 'json', beforeSend: … -
Django Locallibrary Project
I am working on locallibrary projects that mostly everybody did and need to add couple feature, but i could not get it. I need to add return book and take a book method/function for users. Inside myborrow list html I add this borrwed_user.html <a href="{% url 'book-return' bookinst.book.pk %}"> <button>Return it</button> </a> then add url path path('bookreturn/<int:pk>', views.bookreturn, name='book-return'), then add view def bookreturn(request, pk): model = BookInstance.objects.filter(id=pk) model.status = 'a' return render(request, 'catalog/bookinstance_list_borrowed_user.html') but it does not change status of book or drop the book from borrwer. I am missing something but i did not get it. Thank you for your help. -
AttributeError at /payment/ cards
I'm trying to develop an e-commerce website. For some reason, I'm receiving this error, although cards seems to be attributed correctly. My views.py: @login_required def PaymentView(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) order = Order.objects.get(cart=cart) except: the_id = None return redirect(reverse("myshop-home")) if request.method == "POST": try: user_stripe = request.user.userstripe.stripe_id customer = stripe.Customer.retrieve(user_stripe) except: customer = None pass if customer is not None: token = request.POST.get('stripeToken') card = customer.cards.create(card=token) charge = stripe.Charge.create( amount= 400, currency="usd", card= card, customer = customer, description = "Charge for %s" %(self.request.user.username) ) What actually is the problem here? -
how do i run a Script inside django?
enter image description here i created a folder containing the script text.py and init.py in app directory. i have already install Django-extentions, still am getting bugs C:\Users\Qasim\Desktop\translator>python manage.py runscript text No (valid) module for script 'text' found Try running with a higher verbosity level like: -v2 or -v3 C:\Users\Qasim\Desktop\translator>python manage.py runscript text -v2 Check for django.contrib.admin.scripts.text Check for django.contrib.auth.scripts.text Check for django.contrib.contenttypes.scripts.text Check for django.contrib.sessions.scripts.text Check for django.contrib.messages.scripts.text Check for django.contrib.staticfiles.scripts.text Check for news.scripts.text Check for rest_framework.scripts.text Check for django_extensions.scripts.text Check for scripts.text No (valid) module for script 'text' found -
Django allauth example [Errno 111] - Connection refused
I have the following error when login by FB in Django app which was uploaded to heroku: ConnectionRefusedError at /accounts/facebook/login/token/ [Errno 111] Connection refused Did I miss somethings? -
Forms has no attribute form
Hi guys im new to django so i tried to import forms from django and use it to make a section to send out articles and this is the code : from django import forms class SendArticleForm(forms.form): title = forms.CharField() body = forms.CharField(widget = forms.Textarea) published_at = forms.DateField() so after i tried to upload this code and run local server it gave me this error and i cant findout how this is happend. class SendArticleForm(forms.form): AttributeError: module 'django.forms' has no attribute 'form' -
I want to redirect to authenticate url after entering login credentials, but it is simply redirecting to same page that im in
a modal will be popped up after pressing login button, after entering details. I need it to be redirect to the following authenticate Django url. but it is showing the same site again <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#exampleModalCenter"> login </button> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Login</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method="post" action="{% url "authenticate" %}"> <div class="modal-body"> <input type="text" style="margin: 10px;margin-left: auto;margin-right: auto;width: 60%" name="username" class="form-control" placeholder="username"> <input type="password" style="margin: 10px;margin-left: auto;margin-right: auto;width: 60%" name="password" class="form-control" placeholder="password"> </div> <div class="modal-footer"> <input style="margin: auto" type="submit" class="btn btn-danger" name=""> </div> </form> </div> </div> </div> </form></nav> -
Django models queries
I have 3 tables person(id, email,password,type), user_location(id,location,u_id) and reviews(id,review,from_id,to_id). The user_location(u_id) is the foreignkey to person(id). The review(from_id,to_id) is also foreignkey to person(id). So how can i filter out a person with type 'a' and location 'b' and the reviews he got with the reviewers name? -
How to change message design in the real time chat
I have real time chat in the project, where i have two types of users: students and teachers. I want to change design of teacher messages. I tried to change consumers.py and tried to work with template but it didn't work. I think that we can do that, if we'll work with consumers.py. Who knows how to implement that? models.py class CustomUser(AbstractUser,mixins.GuardianUserMixin): email = models.EmailField(_('email_address'), unique=True, name='email') username = models.CharField(_('username'), unique=True, max_length=128) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() consumers.py class Consumer(WebsocketConsumer): def connect(self): self.room_name=self.scope['url_route']['kwargs']['room_name'] self.room_group_name='chat_%s' % self.room_name self.name = self.scope['user'].username if self.scope['user'].is_anonymous: self.send({'close':True}) else: async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type":"chat_message", "message":self.name+" Joined Chat " } ) self.accept() def disconnect(self, code): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type":"chat_message", "message":self.name+" Left Chat" } ) async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data=None, bytes_data=None): text_data_json=json.loads(text_data) message=text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type':'chat_message', 'message':self.name+" : "+message } ) def chat_message(self,event): message=event['message'] self.send(text_data=json.dumps({ 'message':message })) template <div class="ui form"> <div style="height:400px;width:100%;overflow-y:scroll" id="div_data"></div> <input type="text" name="message" id="message" placeholder="Message" style="padding:10px;width:100%; border-radius: 0px;"> <script> var roomName='{{ room_name }}'; var personname='{{ request.user.username }}'; var chatSocket=new WebSocket('ws://'+window.location.host+'/ws/chat/'+roomName+'/'); {% if request.user.is_anonymous %} window.location.pathname = '{% url 'users:login' %}' {% endif … -
Updating duplicate student Information in django
I have a bunch of CSV files that I have made to upload to a django model. 1. Created a view to upload the csv 2. Separated the fields and added them to a variable 3. Called the update_or_create() method to add the information into the model. The problem that I am facing is getting django to update the old row instead of creating a new one. If a student has failed in the first year but passes the next year, the old marks have to be updated. I am trying to filter() with the Register Number of the student and Class to narrow it down. IF there is a student with for instance AAAAAA1111 from BA 1 SEM, and they gave the exam in 2016, 2017 and passed in 2018, the last result has to update the old result. I am enclosing two documents which i used. One is the 2016 result and the second is the 2017 repeaters csv. LINK TO FILES: https://drive.google.com/open?id=1_5cHRKNYdLBYWLhPw_Z4dn-VgX14Amw2 This what my view looks like template = "uploadstudent.html" data = {} if "GET" == request.method: return render(request, template, data) # if not GET, then proceed csv_file = request.FILES["csv_file_student"] if not csv_file.name.endswith('.csv'): messages.error(request,'File is not … -
django download files from a list (s3 as back-end)
I need to list an html table the content of a S3 bucket and enable the option to download the file. To do so I have done he following: The code shows the list of the bucket files correctly, but I'm not sure how I can write the code to download the files. inventory.html: {% block title %} title{% endblock %} {% block content %} <table class="table table-striped"> <thead> <tr> <th scope="col">Date&nbsp;<a href="?order_by=ord_date&direction=desc">{% load static %}<img src="{% static "arrow.png" %}" width="12" height="12" alt="order desc"></a><a href="?order_by=ord_date&direction=asc">{% load static %}<img src="{% static "sort-down.png" %}" width="12" height="12" alt="order asc"></a></th> <th scope="col">Name&nbsp;<a href="?order_by=ord_source&direction=desc">{% load static %}<img src="{% static "arrow.png" %}" width="12" height="12" alt="order desc"></a><a href="?order_by=ord_source&direction=asc">{% load static %}<img src="{% static "sort-down.png" %}" width="12" height="12" alt="order asc"></a></th> <th scope="col">Size</th> <th scope="col">Action</th> </tr> </thead> <tbody> {% for item in items %} <tr> <td>{{ item.LastModified }}</td> <td>{{ item.Key }}</td> <td>{{ item.Size }}</td> <td><button type="Button" class="btn btn-secondary btn-sm"><a href="?key_download={{ item.Key }}">Download</button></a></td> </tr> {% endfor %} </tbody> </table> {% endblock %} views.py: client = boto3.client('s3') def inventory(request): if request.GET.get('key_download'): url = client.generate_presigned_url('get_object', Params = { 'Bucket':'url_of_the_bucket', 'Key':request.GET.get('key_download')}, ExpiresIn = 86400) return **"I don't know how I can return it"** else: fdc_inventories = client.list_objects_v2(Bucket='url_of_the_bucket') fdc_inventories['Contents'].sort(key=itemgetter('LastModified'), reverse=True) return render(request, 'inventory.html', {'items': … -
How can I do a left join in Django?
What I want to do is: select * from employer e left join person p on p.employer.id = e.id and p.valid = True That means that I will see |employer|null| for any employer that does not have a person working for them and I will see the same thing if there is a person working for them but they are invalid. In django I wish I could do: employers.objects.all().values('id', 'person') and have the value of person show up as None rather than show me the invalid person. -
How can I append the page number in the request endpoint
I am having a URL as below: HTTP Request Method : GET Endpoint: http://localhost:8000/api/<client_id>/getshowscount I am using a paginator class in my Django code. class ShowListPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 1000 class ClientShowSongListViewSet(viewsets.ModelViewSet): permission_classes = (DashboardAccess,) serializer_class = ShowCountSerializer pagination_class = ShowListPagination def get_queryset(self): return ShowSong.objects.filter(user = self.request.user) Everything works fine. But, the requirement says that I need to have URL endpoint as below: Endpoint examples: http://localhost:8000/api/<client_id>/getshowscount/?page=1 http://localhost:8000/api/<client_id>/getshowscount/?page=2 By the above endpoint examples, I mean to say that I need to append the page also in the URL depending upon the pages. I checked the paginator class. But I didn't find anything useful. Can anyone suggest some workarounds for the same? -
basic django site gives error as "Not found: /nettrack/
I am totally new to django and stuck with basic learning of django. I have below structure of django project: G:\virtualenvs\Netsite\netmon-- enter image description here I have below urls.py under netmon enter image description here I have below urls.py under nettrack enter image description here This is basic_generic.html And I have below index.html enter image description here Now, whats wrong? I get error as below in the cmd window of "python manage.py runserver" enter image description here Please help. Also, I dont know whether I need any IIS running on my windows desktop machine so as to test site as http:/127.0.0.1:8000/nettrack/ in edge browser. -
How to get large-size scraped data quickly?
I select news from one website and display it on my page. But when I go to the news tab or refresh the page, the page loads data for a while (10 seconds). How can I upload data instantly? I tried to load data, but the problem is that if the text to the article is too large, the page load will still not be instantaneous. Maybe i can upload text in chunks some way? My code: def get_summary(url): new_d = BeautifulSoup(requests.get(url).text, 'html.parser') return '\n'.join(i.text for i in new_d.find('div', {'class':'flexible_content_wrap'}).find_all('p')) def scrape(request): website_url = requests.get("https://loudwire.com/news/").text soup = BeautifulSoup(website_url, "html.parser") more = [] teaser = soup.find_all('div', {'class':'teaser_feed_common'}) for i in teaser: mine = get_summary(i.a['href']) print(mine) more.append(mine) context = {'more_info': more} return render(request, 'music/news.html', context) In advance, thanks for any help. -
cannot resolve keyword 'user' into field - django error
this is the error message I am getting --->Cannot resolve keyword 'user' into field. Choices are: date_joined, email, emailconfirmed, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, order, password, profile, user_permissions, useraddress, userdefaultaddress, username, userstripe<---- it is highlighting these two pieces of code as key areas as where the problem seems to arise. new_order = Order.objects.get(cart=cart) ///// new_order.user = User.objects.get(user=request.user) all help would be greatly appreciated in solving this! views.py - orders import time import stripe from django.contrib.auth.decorators import login_required from django.conf import settings from django.contrib.auth.models import User from django.shortcuts import render, HttpResponseRedirect from django.urls import reverse # Create your views here. from users.forms import UserAddressForm from carts.models import Cart from .models import Order from users.models import Profile, UserAddress, UserAddressManager from .utils import id_generator stripe.api_key = settings.STRIPE_SECRET_KEY def orders(request): context = {} template = "orders/user.html" return render(request, template, context) @login_required def checkout(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse("cart")) try: **new_order = Order.objects.get(cart=cart)** except Order.DoesNotExist: new_order = Order() new_order.cart=cart **new_order.user = User.objects.get(user=request.user)** new_order.order_id = id_generator() new_order.final_total = cart.total new_order.save() except: return HttpResponseRedirect(reverse("cart")) try: address_added = request.GET.get("address_added") except: address_added = None if address_added is None: address_form = UserAddressForm() else: address_form = None current_addresses = … -
syntax error in using SECRET_KEY in __init__py in django
I have read that it is not secure to store the SECRET_KEY in settings.py as its default. So, I decided to store it in my __init__.py. I wrote in __init__.py which is beside settings.py: export SECRET_KEY= 'hf7^vrmc!^agnpba#^+$9ac-@eullgd-=ckq&u1zu$b7nqc)%_' This is the only line in my __init__.py. Then in settings.py I changed the line SECRET_KEY = 'hf7^vrmc!^agnpba#^+$9ac-@eullgd-=ckq&u1zu$b7nqc)%_' into SECRET_KEY = get_env_variable('SECRET_KEY') but when I try to runserver, I receive Syntax error as below: … __init__.py", line 1 export SECRET_KEY= 'hf7^vrmc!^agnpba#^+$9ac-@eullgd-=ckq&u1zu$b7nqc)%_' ^ SyntaxError: invalid syntax What's wrong here? Thank you in advanced. -
django dynamically loading a static file
I am trying to send a static link to a download button. The static link results in a views.py function and will be returned as a dict. in views.py: def some_fct(request): handling the request return render(request,'site.html',{'processed_request': 'name_of_static_file'}) I tried to locate the data in a seperate div and change the href with: <div id="data">{{processed_request}}<\div> <a href="" id="download"><button class="download_btn"><i class="fa fa-download"></i> Download</button></a> <script> let file = document.getElementbyId('data').innerHTML; let file_static = "{% static '${file}' %}" document.getElementById('download').setAttribute("href",file_static); </script> which leads to the console.log https://..../static/%24%7Bfile%7D instead of https://..../static/name_of_static_file How can I access the static_file? -
ImportError: cannot import name 'BaseContact'
I have a problem while running my Django code. File "E:\sophienwald\amocrm\models.py", line 3, in <module> from amocrm import BaseContact, amo_settings, fields, BaseLead ImportError: cannot import name 'BaseContact' But I noticed a strange feature... If I swap "BaseContact" and "BaseLead" it says that compiler can't import BaseLead. "fields" and "amo_setting" work fine. Bit of code from amocrm\models.py: import logging from amocrm import BaseContact, amo_settings, fields, BaseLead from django.conf import settings from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.functional import cached_property from wagtail.admin.edit_handlers import MultiFieldPanel, FieldPanel from wagtail.contrib.settings.models import BaseSetting from wagtail.contrib.settings.registry import register_setting logger = logging.getLogger(__name__) @register_setting class AmocrmSettings(BaseSetting): PIPELINE_FIELDS = [ ('stay_tuned_pipeline_name', 'stay_tuned_status_name'), ('new_posts_pipeline_name', 'new_posts_status_name'), ('back_call_pipeline_name', 'back_call_status_name'), ] login = models.CharField('Логин', max_length=120, null=True, blank=True) token = models.CharField('Токен', max_length=120, null=True, blank=True) subdomain = models.CharField('Поддомен', max_length=120, null=True, blank=True) run_async = models.BooleanField('Обновлять асинхронно', default=False) # forms.StayTunedContact stay_tuned_pipeline_name = models.CharField('Название воронки', max_length=120, null=True, blank=True) stay_tuned_status_name = models.CharField('Статус при создании', max_length=120, null=True, blank=True) # forms.NewPostsContact new_posts_pipeline_name = models.CharField('Название воронки', max_length=120, null=True, blank=True) new_posts_status_name = models.CharField('Статус при создании', max_length=120, null=True, blank=True) # forms.BackCallContact back_call_pipeline_name = models.CharField('Название воронки', max_length=120, null=True, blank=True) back_call_status_name = models.CharField('Статус при создании', max_length=120, null=True, blank=True) panels = [ MultiFieldPanel([ FieldPanel('login'), FieldPanel('token'), FieldPanel('subdomain'), FieldPanel('run_async'), ], 'Авторизация'), ] -
Show the download button only if file is available on server in Django template (html)
Following code shows the download option on the page whether file is present or not on server. <a href="{%static 'media/reports/finance'%}/sap-daily.csv" download >Download</a> I want to show not available option if the file is not present on server. -
How can I access serializer's field data before its type validation?
How to access the field value before serialization in my serializer (serializers.Serializer) or rest view (UpdateAPIView)? I have something like this: class MySerializer(serializers.Serializer): my_field = serializers.IntegerField() If I try to fill my field with 'test' string, it will immediately raise the ValidationError telling me about wrong data type (expecting an integer number of course). Before that error raise, I want to capture the value and do something with it but I have no idea how and where can I access it. It has an empty string value everywhere. I tried to get it in is_valid() before call super() or with raise_exception=False, but I still can not see it: '_kwargs': {'context': {'format': None, 'request': <rest_framework.request.Request object>, 'view': <rest.views.MyUpdateAPIView object>}, 'data': <QueryDict: {'my_field': ['']}>, 'initial_data': <QueryDict: {'my_field': ['']}>, When I try to find it in my view I can also see nothing: serializer.initial_data <QueryDict: {'my_field': ['']}> request.data <QueryDict: {'my_field': ['']}> When I try to check validate() or validate_my_field() methods, I can not even get there because of the ValidationError I mentioned above. How the serializer validation actually works? What is the order in it and how can I access data before it is "cleaned"? -
Authentication in Django Channels v2 tests with WebSocketCommunicator
In the process of writing tests for my chat consumer I encountered with a problem of being unable to authenticate in tests, using WebSocketCommunicator. I have custom JwtTokenAuthMiddleware that implements authentication in sockets by using token in request query, because as I know, decent authentication with the use of authorization headers is not possible yet. Can you guys advise me on that or provide me with the example code, which I couldn't find across the net ? Btw, my chat is working without problems. Also tests should be perfectly fine, I took the guide from official documentation Django Channels 2.x Testing. --JwtTokenAuthMiddlewate-- class JwtTokenAuthMiddleware: def __init__(self, inner): self.inner = inner def __call__(self, scope): close_old_connections() try: raw_token = scope['query_string'].decode().split('=')[1] auth = JWTAuthentication() validated_token = auth.get_validated_token(raw_token) user = auth.get_user(validated_token) scope['user'] = user except (IndexError, InvalidToken, AuthenticationFailed): scope['user'] = AnonymousUser() return self.inner(scope) JwtTokenAuthMiddlewareStack = lambda inner: JwtTokenAuthMiddleware(AuthMiddlewareStack(inner)) --Example Test-- @pytest.mark.django_db(transaction=True) @pytest.mark.asyncio async def test_trainer_auth_success(): room = await database_sync_to_async(RoomFactory.create)() trainer = room.trainer trainer_token = await sync_to_async(get_token_for_user)(trainer.user) room_url = f'ws/room/{room.id}/' trainer_communicator = WebsocketCommunicator(application, f'{room_url}?t={trainer_token}') connected, _ = await trainer_communicator.connect() assert connected trainer_connect_resp = await trainer_communicator.receive_json_from() assert_connection(trainer_connect_resp, [], room.max_round_time) await trainer_communicator.disconnect() --Traceback of Error-- ___________________________________________________________ test_trainer_auth_success ___________________________________________________________ self = <channels.testing.websocket.WebsocketCommunicator object at 0x7f6b9906f290>, timeout = 1 …