Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to resolve SMTP error in pythonanywhere
i'm deploying my django project using pythonanywhere, in my code i will send an activation like to the user after he/she has opened an account, but that line isn't being run, i' getting an error which says: SMTPSenderRefused at / (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError q185sm6000383qke.25 - gsmtp', 'webmaster@localhost') -
django edit profile form does not save
The edit profile form does not save any data that is modified. i believe the problem might be with my get requests or my loops. No error shows on my terminal when i click add. it just redirects to the http response. I might be passing data wrongly also. ediprofile.html <form method="post">{% csrf_token %} {{form.first_name}} {{form.last_name}} {{form.email}} {{form.phonenumber}} {{form.state}} {{form.next_of_kin}} {{form.dob}} {{form.address}} <li class="btnn"><button type="submit" class="conf">Add</button></li> </form> <h1 class="cer">{{ form.errors.password1 }}{{form.errors.username}}{{form.errors.first_name}} {{form.errors.last_name}} {{form.errors.email}} {{form.errors.phonenumber}} {{form.errors.address}} {{form.errors.password2}} </h1> forms.py class EditProfileForm(UserCreationForm): first_name = forms.CharField(max_length=100, help_text='First Name') last_name = forms.CharField(max_length=100, help_text='Last Name') address = forms.CharField(max_length=100, help_text='address') next_of_kin = forms.CharField(max_length=100, help_text='Next of kin') dob = forms.CharField(max_length=100, help_text='Date of birth') state = forms.CharField(max_length=100, help_text='State') phonenumber = forms.CharField( max_length=100, help_text='Enter Phone number') email = forms.EmailField(max_length=150, help_text='Email') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['email'].widget.attrs.update( {'placeholder': ('Email')}) self.fields['address'].widget.attrs.update( {'placeholder': ('Address')}) self.fields['phonenumber'].widget.attrs.update( {'placeholder': ('Phone number')}) self.fields['first_name'].widget.attrs.update( {'placeholder': ('First name')}) self.fields['last_name'].widget.attrs.update( {'placeholder': ('Last name')}) self.fields['dob'].widget.attrs.update( {'placeholder': ('Date of birth')}) self.fields['state'].widget.attrs.update({'placeholder': ('State')}) self.fields['next_of_kin'].widget.attrs.update( {'placeholder': ('Next of kin')}) self.fields['first_name'].widget.attrs.update({'class': 'log'}) self.fields['last_name'].widget.attrs.update({'class': 'log'}) self.fields['email'].widget.attrs.update({'class': 'log'}) self.fields['phonenumber'].widget.attrs.update({'class': 'log'}) self.fields['address'].widget.attrs.update({'class': 'log'}) self.fields['dob'].widget.attrs.update({'class': 'log'}) self.fields['state'].widget.attrs.update({'class': 'log'}) self.fields['next_of_kin'].widget.attrs.update({'class': 'log'}) class Meta: model = User fields = ('first_name', 'last_name', 'phonenumber', 'email', 'address', 'dob', 'state', 'next_of_kin') views.py def edit_profile(request,id): profile = Profile.objects.get(user_id=id) user = get_object_or_404(Profile, pk=id, user=profile.user.id) if … -
Voice Modulator Using Django Framework
I want to make a voice modulator using python language. The backend framework i am using is django. But i am facing issue in finding an api written in python which could help me in integrate voice modulator in my platform. Or if no such api exists then can you please guide in how can i get started to make modulator. What stuff would be used?? -
How to get list of related object in annotion when using Greatest function in django models
I am having two models, a User model and a Payment model and there is on to many relationship between them. User has multiple Payments. What I am trying to achieve is sorting the User model as per the Payment's created_at field. I am trying to modify the Queryset and then I'll be using the annotated field latest_tran for sorting. def get_queryset(self, request): qs = super(ClubbedPaymentAdmin, self).get_queryset(request) qs = qs.annotate( latest_tran=Greatest(Payment.objects.filter(user=F('id')).values_list('created_at', flat=True))) return qs But I am having below error Greatest must take at least two expressions So it seems like I am making a mistake when evaluating the list of Payments. Or may be like I am taking a wrong approach. Any help would be much appreciated. Thank you. -
I am not able to run blockchain.py
I am new to flask . I am testing a blockchain that i found on github and i am facing this error: Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) [2020-10-04 21:37:54,221] ERROR in app: Exception on /mine_block [GET] Traceback (most recent call last): File "C:\Users\T357\anaconda3\lib\site-packages\flask\app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "C:\Users\T357\anaconda3\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\T357\anaconda3\lib\site-packages\flask\app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Users\T357\anaconda3\lib\site-packages\flask_compat.py", line 33, in reraise raise value File "C:\Users\T357\anaconda3\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\T357\anaconda3\lib\site-packages\flask\app.py", line 1598, in dispatch_request return self.view_functionsrule.endpoint File "C:\Users\T357\Desktop\blockchain.py", line 84, in mine_block return jsonify(response), 200 File "C:\Users\T357\anaconda3\lib\site-packages\flask\json.py", line 251, in jsonify if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr: File "C:\Users\T357\anaconda3\lib\site-packages\werkzeug\local.py", line 347, in getattr return getattr(self._get_current_object(), name) AttributeError: 'Request' object has no attribute 'is_xhr' 127.0.0.1 - - [04/Oct/2020 21:37:54] "←[35m←[1mGET /mine_block HTTP/1.1←[0m" 500 - as you can see the error is AttributeError: 'Request' object has no attribute 'is_xhr' so can anyone lead me in the right direction ,i cant find a solution on my own. thanks -
Displaying 3 separate forms on the same page in django
So I'm working on a single page site which is to have 3 different forms on the same page. Tour form, flight form and bookform I created the forms using model form but how do I display the forms such that my site will know which form I'm submitting data to -
TemplateDoesNotExist at /groups/posts/in/first-post/ post/_post.html
I am following along on a tutorial (which is from two yrs ago so they are using an older version of django and python), i finished the blog, everything works fine, i can register, login, post a new forum, but when i click to see a blog post already created i get the error below. Overall, I'm not sure where the problem is, is it in in _post.html, views.py, models.py urls.py? TemplateDoesNotExist at /groups/posts/in/first-post/ post/_post.html here is my base.html: <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>Star Social</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet"> {# NOTE: To use the static, you must put the loadstatic files at the beggining #} <link rel="stylesheet" href="{% static 'simplesocial/css/master.css' %}"> </head> <body> {# mynav is my own class to setup my css#} <nav class="navbar mynav" role="navigation" id="navbar"> <div class="container"> <a class="navbar-brand mynav" href="{% url 'home' %}">Star Social</a> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li><a href="{% url 'posts:create' %}">Post</a></li> <li><a href="{% url 'groups:all' %}">Groups</a></li> <li><a href="{% url 'groups:create' %}">Create group</a></li> <li><a … -
Value repeated inside get function in Django serializer
I try to get value from django serializer inside another serializer class to update it. Getting the value is done with serializers.SerializerMethodField() and get. But when I loop the Json value inside the API it returns too much queries (30 raws return 30 queries) I expected [1, 2, 3,] I have [1, 2, 3] [1, 2, 3] [1, 2, 3] The code: class SerializerA(serializers.ModelSerializer): dimension = serializers.SerializerMethodField() @staticmethod def get_dimension(self): list_apps = SerializerB.objects.values_list('list_apps', flat=True)[0] dim = [item['wth'] for item in list_apps] return dim class Meta: ... If I put list_apps and dim outside the def it works well. I don't know how to do (exit list_apps and dim outside the def or get I expected (one line)). Thanks ! -
Serialize relations in django
I have 2 models --> Candidate and Grade. 1 Candidate have many Grade. I want to return from rest API average grade from many grades that one Candidate can receive. How can I doing this. My model: class Candidate(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class Grade(models.Model): value = models.IntegerField(blank=True, null=True) candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, related_name='grades') My serializers.py from rest_framework import serializers from .models import Candidate, Grade class CandidateSerializer(serializers.ModelSerializer): pk = serializers.SerializerMethodField('get_pk_from_candidate') full_name = serializers.SerializerMethodField('get_full_name_from_candidate') grades = serializers.SlugRelatedField(many=True, read_only=True, slug_field='value') class Meta: model = Candidate fields = ['pk', 'full_name', 'avg_grade', 'grades'] def get_pk_from_candidate(self, candidate): return candidate.id def get_full_name_from_candidate(self, candidate): data = (candidate.first_name, candidate.last_name) full_name = ' '.join(data) return full_name I want my JSON format like below: { "pk": 3, "full_name": "rafał małek", "avg_grade": "", "grades": [ 12, 4, 13, 5 ] }, -
ModelForm has no model class specified.[django]
In my forms i have: class SignUpForm(UserCreationForm): username = UsernameField(label=_("Username"), widget=forms.TextInput(), ) email = forms.EmailField(max_length=254, label="Email", widget=forms.EmailInput(), validators=[EmailValidator]) class Meta: model = locate(settings.AUTH_USER_MODEL) <--- HERE fields = ("username", "email", "password1", "password2") in user app in models: class Profile(AbstractUser): def __str__(self): return self.username In my project settings.py I set up AUTH_USER_MODEL = 'user.Profile' And it gives me ValueError at /user/register ModelForm has no model class specified. When I change class Meta in my form to: class Meta: model = Profile <--- HERE Everything is OK. Why my model = locate(settings.AUTH_USER_MODEL) doesnt work? -
How to create a line chart indicating which month a user wrote more or less blogs?
This is how I want the output - According to the above chart, the user wrote lots of posts between March and April, and then in the month of July the number is decreased. I worked with tables and pie charts but couldn't make this one work. Here is a sample of the Django model can be used for this purpose: class Blog(models.Model): title = models.CharField(max_length=160) ... created_at = models.DateTimeField(auto_now_add=True) I know the data to be used here can be extracted from created_at field but I don't know how to do the JavaScript part. If I pass {"blogs": Blog.objects.all()} context in template how do I plot above like line bar. Please help. Thank You. -
How can I render new HTML content in Django template?
I'm a beginner in Django. In my template file, I have the following: <select id="selectbox"></select> <div id="containerdiv"></div> Within the containerdiv, I can return a HttpResponse such as: <form> <!-- some more input elements here --> </form> so now I will have a new form within the div. The content of the form will change depending on the value of selectbox. However, I also have {% csrf_token %} tag within the rendered HttpResponse which is not being rendered properly. Is this even the correct way to work with Django? -
Django+Channels+Heroku deployment with Daphne: Closing Postgre connections
My Django webapp deploys fine, however my db connections max out after a few queries to Postgres. Here is my understanding of my problem: Db connections to Postgres are opened for every query but not closed and this results is a db timeout once max connections is reached. Heroku documentation for this error, but I think that whatever new number of connections are enabled through an upgrade, those connections will also max out fast. (Or am I wrong?) pg:killall is not a solution to my problem. The solution must not be manual in this application. I have used Heroku documentation for Concurrency and DB connection in Django This SO question is related but answers don't solve my problem Debug error FATAL: too many connections for role "DB_username" Running heroku pg:info --app appname in cmd === DATABASE_URL Plan: Hobby-dev Status: Available Connections: 20/20 <<<<<<<<<<<<<<<<<<<<< PG Version: 12.4 Created: 2020-09-11 16:57 UTC Data Size: 9.3 MB Tables: 15 Rows: 85/10000 (In compliance) Fork/Follow: Unsupported Rollback: Unsupported Continuous Protection: Off Add-on: postgresql-infinite-00894 Here are the things I have tried: setting dj_database_url.config(conn_max_age==0,...) Using Pgbouncer to pool connections Disabling server side cursors Settings.py # PRODUCTION SETTINGS MIDDLEWARE.append('whitenoise.middleware.WhiteNoiseMiddleware') DATABASE_URL = os.environ['DATABASE_URL'] DISABLE_SERVER_SIDE_CURSORS = True SECRET_KEY = … -
Object value is not showing in frontend (react js) | django
Though my code is working fine at backend. But can't figure out why data is not passing through react.js. Hopefully, it's just a simple error. Why these {this.state.article.title} and {this.state.article.content} values are not showing? view.js export default class ArticleDetail extends React.Component { state = { article: {} } componentDidMount() { const articleID = this.props.match.params.articleID; axios.get(`http://127.0.0.1:8000/api/${articleID}`).then( res => { this.setState({ article: res.data }); } ) } render (){ return ( <div> <Card title={this.state.article.title}> // it's not showing <p> {this.state.article.content} </p> // it's not showing </Card> <CustomForm/> </div> ) } } models.py class Article(models.Model): title = models.CharField(max_length=20) content = models.TextField() -
Template does not exist in django, but I have template?
I have a problem. I use django 3.1.1 and python 3.8.5/ I try to create a site in python + django (back-end) and html, css, bootstrap (front-end). I created two applications 1. blog (in one subpage I will have blog) and 2. Pages other subpages like homepage. This is my whole program https://github.com/Charnel2500/blog_ai_py385_django311 My blog works perfectly (I create this application from a tutorial) Now I try to create another application by my own - "pages". I created a new application. I add this application in settings.py (and in DIR) """ Django settings for ai_blog project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '-%60+qrw+)3c&_tchqlyt8=%k$@b331pw1se*=lsr#21ux7g=$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', '.pythonanywhere.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'pages', … -
ModuleNotFoundError: No module named 'sorl'
I'm getting following error during installing django-oscar from https://django-oscar.readthedocs.io/en/2.0.4/internals/getting_started.html settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'oscar', 'oscar.apps.analytics', 'oscar.apps.checkout', 'oscar.apps.address', 'oscar.apps.shipping', 'oscar.apps.catalogue', 'oscar.apps.catalogue.reviews', 'oscar.apps.partner', 'oscar.apps.basket', 'oscar.apps.payment', 'oscar.apps.offer', 'oscar.apps.order', 'oscar.apps.customer', 'oscar.apps.search', 'oscar.apps.voucher', 'oscar.apps.wishlists', 'oscar.apps.dashboard', 'oscar.apps.dashboard.reports', 'oscar.apps.dashboard.users', 'oscar.apps.dashboard.orders', 'oscar.apps.dashboard.catalogue', 'oscar.apps.dashboard.offers', 'oscar.apps.dashboard.partners', 'oscar.apps.dashboard.pages', 'oscar.apps.dashboard.ranges', 'oscar.apps.dashboard.reviews', 'oscar.apps.dashboard.vouchers', 'oscar.apps.dashboard.communications', 'oscar.apps.dashboard.shipping', # 3rd-party apps that oscar depends on 'widget_tweaks', 'haystack', 'treebeard', 'sorl.thumbnail', 'django_tables2', ] HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', 'URL': 'http://127.0.0.1:8983/solr', 'INCLUDE_SPELLING': True, }, } After running py .\manage.py migrate or py .\manage.py makemigrations I got following error Traceback (most recent call last): File ".\manage.py", line 21, in main() File ".\manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\projects\ecommerce\django-oscar-env\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "D:\projects\ecommerce\django-oscar-env\lib\site-packages\django\core\management_init_.py", line 377, in execute django.setup() File "D:\projects\ecommerce\django-oscar-env\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\projects\ecommerce\django-oscar-env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "D:\projects\ecommerce\django-oscar-env\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "c:\program files\python37\lib\importlib_init_.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'sorl' I have also found that solr-thumbanil or solr is not install. If I install solr-thumbnail then I get following error … -
Is it possible to lock the database for editing , and edit only through the django app?
i need to lock postgres sql database for editing from anywhere even with direct admin access and just edit with the Django app, I mean the app itself, not the user and the database password -
Name Error in Django - Nested Views Function - Saving to Database
Using Django, While trying to save the answers from the User to the Database, it is showing me a Name Error. I have used a nested function inside the views function, it works correctly when i do not attempt to save the data to the database. But once i try to put in code inside the views function to save the data, it produces this name error. Below are the files with the code, models.py file from django.db import models from django.utils import timezone from django.contrib.auth.models import User class ansquestions(models.Model): m_invested = models.CharField(max_length=100) p_return = models.CharField(max_length=100) years = models.CharField(max_length=100) inflation_yes_no = models.CharField(max_length=100) r_output = models.TextField(default=True) date_answered = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) form.py file from django import forms from .models import ansquestions class ansquestionsForm(forms.ModelForm): class Meta: model = ansquestions fields = ['m_invested', 'p_return', 'years', 'inflation_yes_no', 'r_output', 'date_answered', 'author' ] views.py file from django.shortcuts import render #from django.http import HttpResponse from .models import ansquestions from .forms import ansquestionsForm def investmentfv(request): idata = { 'tmi':tmi, 'pry':pry, 'ys':ys, 'qinf':qinf } return render(request, 'fvalueapp/investmentfv.html', idata) def investmentfvcalc(request): total_i = request.POST["m_invested"] perc_r = request.POST["p_return"] years_i = request.POST["years"] makeup_infl = request.POST["inflation_yes_no"] def fvinvestment(): global fv_i_value global r_output #global makeup_infl ( global variable might be needed for … -
ModuleNotFoundError: No module named 'tinymce' while trying to deploy on pythonanywhere
I think I have all the necessary libraries installed pip freeze gives this output asgiref==3.2.10 astroid==2.4.2 Django==3.1.2 django-appconf==1.0.4 django-tinymce==3.1.0 django-tinymce-lite==0.0.2 lazy-object-proxy==1.4.3 Pillow==7.2.0 pytz==2020.1 six==1.15.0 sqlparse==0.3.1 wrapt==1.12.1 I've tried importing tinymce in python console and it gets imported but still I am getting this error. I know this question is repetitive but solutions to other threads ain't working. Also, collectstatic gives the following error ImportError: cannot import name 'HTMLField' from 'tinymce' -
403 error from Vuejs axios.post logout to DjangoAPI
I have a project uses Django API and VueJS project. I need help about logging out an User. I can login and register user succesfully but while trying to logout; I click button and nothing happens and in the network I get 403 error.But when I re-enter page, user is logged out. This is how I try to logout. User clicks button: <b-link @click.prevent="logout"> Çıkış Yap </b-link> async logout() { // call loginUSer action await this.$store.dispatch('user/logout', {}) .then(() => { this.wrongCred = true this.$router.push('/') }) .catch(err => { console.log(err) this.wrongCred = true // if the credentials were wrong set wrongCred to true }) }, In vuex module: async logout(context) { try { const response = await DjangoAPI.logout(); context.commit('reset'); return Promise.resolve(response); } catch(err) { console.log('err in store.user/logout', err); return Promise.reject(err); } } and in DjangoUserService.js: import axios from "axios"; import Cookies from 'js-cookie'; const apiCall = process.env.NODE_ENV === 'test' ? axios : HTTP; var csrftoken = Cookies.get('csrftoken'); async logout(payload) { try { console.log(payload); const response = await apiCall.post(`/api/rest-auth/logout/`,{}, { headers: {"X-CSRFToken": csrftoken } }); return Promise.resolve(response); } catch(err) { console.log('err in DjangoService/logout', err); return Promise.reject(err); } } and I have an interceptor which I think is not good but I am … -
Django 3.1 - annotation, ExpressionWrapper and division - SQL error
I am building a query, that filters on a frequency field. Now the frequency is not a model field, but an annotated value, derived from a duration and a count. This is based on the very basic idea that frequency = duration / number of times stuff happened. (Very) simplified models are below: import uuid class Actor(AbstractBaseUser): uuid = models.UUIDField(_('UUID'), default=uuid.uuid4, primary_key=True) class Event(models.Model): actor = models.ForeignKey(Actor, null=True, blank=True, on_delete=models.CASCADE) foo = models.CharField(_('Foo'), max_length=10, blank=True, null=True) bar = models.CharField(_('Bar'), max_length=10, blank=True, null=True) when = models.DateTimeField(_('When'), null=True, blank=True) The idea behind the query is this: each actor gets annotated with event_count: the number of Event objects it is the parent of each actor gets annotated with first_event_datetime: the datetime of its earliest child Event object each actor gets annotated with the duration_over: the duration between Now() (database function) and first_event_datetime each actor gets annotated with the "event_frequency" of events over the considered period event_frequency: duration_over / event_count With that in mind, the query is built like this: from django.db import models from django.db.models import Q, Sum, Avg, F, Count, OuterRef, Subquery, Exists, Value, ExpressionWrapper from django.db.models.functions import Coalesce, Now, Mod, Cast actors = Actor.objects.annotate( event_count=Coalesce(Subquery( Event.objects.filter(Q()).values( 'actor__pk' ).order_by( 'actor__pk' ).annotate( count=Count('pk', … -
Getting 403 Forbidden Error in Django Ajax even after passing CSRF_TOKEN
I am using modal pop up box to create instances of Modal in Django. Here is the form inside the modal body: <form action="{% url 'projects:techs_create' %}" method="post" id="tech-form" > {% csrf_token %} <input type="text" name="name" id="tech-name" /> <input type="submit" value="Save" class="button button-main" /> </form> and this is the Ajax request I used $(document).on("submit", "#tech-form", function (e) { e.preventDefault(); $.ajax({ type: "POST", url: $(this).attr("action"), dataType: "json", contentType: "application/json", // data: $(this).serialize(), data: { name: $("#tech-name").val(), csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val(), }, success: function (response) { console.log('done') }, error: function (xhr, status, error) { console.log(error.msg); }, }); }); I get this error: POST http://localhost:8000/techs/new/ 403 (Forbidden) I saw some similar questions here in SO and majority of the answers were talking about a missing csrf token. Now that I added it as data of request. I am still getting the error. What am I doing wrong here? this is the view I am using to handle the request: @login_required def techs_create_view(request): if not request.user.is_superuser: raise PermissionDenied if request.method == 'POST': form = ProjectTechnologieForm(request.POST) if form.is_valid(): name = form.cleaned_data.get('name') form.save() messages.success(request, f'{name} created successfully.') return HttpResponseRedirect('projects:statistics') form = ProjectTechnologieForm() context = { 'tech_form': form } if request.is_ajax(): html = render_to_string('projects/statistics.html', context, request=request) return JsonResponse({'form': html}) … -
how to get connected clients in flask
hi i need to display total number of connected clients on my flask app i write this code for checking connected and disconnected connections. app = Flask(__name__) socketio = SocketIO(app) clients = [] @socketio.on('connect', namespace='/') def connect(): clients.append(request.namespace) @socketio.on('disconnect', namespace='/') def disconnect(): clients.remove(request.namespace) then i render template like this return render_template_string(TABLE_TEMPLATE, data=data, clients=len(clients)) In html part i call like this <h1>{{ clients }} </h1> but on webpage it keep showing 0 even client is connect i get output from client and it is connected it should print 1 2 depends how many clients are connected. even if i print this print(len(clients)) it return 0. even my client is connect and i get output. this is my full code from flask import Flask, request, render_template_string from flask_socketio import SocketIO app = Flask(__name__) socketio = SocketIO(app) clients = [] @socketio.on('connect', namespace='/') def connect(): clients.append(request.namespace) @socketio.on('disconnect', namespace='/') def disconnect(): clients.remove(request.namespace) TABLE_TEMPLATE = """ <h1>{{ clients }} </h1> <style> table, th, td { border: 1px solid black; } </style> <table style="width: 100%"> <thead> <th>Client</th> <th>IP</th> <th>Status</th> </thead> <tbody> {% for row in data %} <tr> <td><center>{{ row.client }}</td></center> <td><center>{{ row.ip }}</td></center> <td><center>{{ row.status }}</td></center> </tr> {% endfor %} </tbody> </table> """ @app.route("/device_add", methods=['POST']) def … -
Django Rest Framework gets 'NoneType' from JS fetch
This is my JS fetch data var requestOptions = { mode:'cors', method: 'POST', redirect: 'follow', headers:new Headers({ "Accept":"application/json,*/*", "Content-Type": "application/json" }), body:JSON.stringify({"username":username_to_test}) }; views.py @api_view(['POST']) #Response will be in JSON format @renderer_classes([JSONRenderer]) def username_check(request): try: isAvailable=db_handle.username_check(request.POST.get("username").lower()) return Response(isAvailable,status=status.HTTP_200_OK) except Exception as e: print("Username check errors",e) return Response(status=status.HTTP_400_BAD_REQUEST) But django-rest-framework never gets the 'username'.It always gets 'NoneType' But the follwoing fetch works var formdata = new FormData(); formdata.append("username",username_to_test); var requestOptions = { mode:'cors', method: 'POST', redirect: 'follow', body:formdata, }; I included JSON parser in Default parsers.But no change.What to do? -
Not able to send messages over sockets Django Channels
I'm unable to send messages to other members of the group when a participant sends a message over the socket. Here's my code. def process_message_and_send_to_other_users(data): # Do some processing and send data to other users of the group. func = get_channel_layer().group_send kwargs = { 'group': str(group_id), 'message': {"type":"push_to_client_socket", "a":1} } # Function not getting called. return func(**kwargs) class Consumer(AsyncJsonWebsocketConsumer): """Consumer.""" async def connect(self): # Accept the connection await self.accept() # Adding current to group. await self.channel_layer.group_add(group=user_id, channel=current) async def disconnect(self, close_code): # Dropping from group. await self.channel_layer.group_discard( group=user.user_id, channel=connection_id, ) async def receive_json(self, data, **kwargs): """Receive messages over socket.""" ######## DO SOME PROCESSING. ##### a = process_message_and_send_to_other_users(data) await self.send_json(resp) async def push_to_client_socket(self, event): """Push the message over the client socket.""" event.pop('type', '') await self.send_json(json.dumps(event, default=str)) Where exactly I'm going wrong? Pls, don't recommend processing the message inside receive_json itself. The above snippet is just a barebone.