Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Profile Pictures Only Showing On One Page, All Other Pages Have A Broken Picture Box
I am not sure why profile pictures are only showing up on one page within my Django Social Media Site. The other pages have a broken picture box. I think that Django is not reading the src of my img tag. Please let me know what you need to see. Thanks, Daniel -
Django REST Framework] AssertionError: Class Serializer missing "Meta" attribute
I'm following the DRF tutorial instructions at https://www.django-rest-framework.org/tutorial/1-serialization/ but an assertion error happened. Here are my codes.(They're exactly the same as the codes from the tutorial website.) I know that class: Meta is required when ModelSerializer is used. But here I used Serializer not ModelSerializer. models.py from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()]) class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) class Meta: ordering = ['created'] serializers.py from rest_framework import serializers from .models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) code = serializers.CharField(style={'base_template': 'textarea.html'}) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Snippet.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the validated data. """ instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.linenos = validated_data.get('linenos', instance.linenos) instance.language = validated_data.get('language', … -
parse json object in django view
I have a form than i need to check if the emails on my form are valid or not here is my ajax code : <script type="text/javascript"> $(document).ready(function (event) { function ValidateEmail(mail) { if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail)) { var postEmail = $("div.postEmail"); if (!$("#members_email").val() == "" || !$("#members_email").val() == null) { $.post( "{%url 'validate_email' %}", { email: $("#members_email").val() }, function (data, status) { console.log("Data: " + JSON.stringify(data) + " " + status); postEmail.append(JSON.stringify(data)); // contaner.append("Data: " + JSON.stringify(data)); } ); }; console.log('email is true'); return (true); } console.log('email is false'); return (false) } and this is my code in django view: def validate_email(request): data = json.loads((request.POST.get('postEmail'))) status=True return JsonResponse(status, safe=False) it raises this error : TypeError: the JSON object must be str, bytes or bytearray, not 'NoneType' thanks in advance -
Page not found (404)- in every page of my project
i am new in django . i work on a project. i use crispy-form in my project. it is my users views :: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm from django.contrib.auth import login, authenticate from django.views.generic import CreateView from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin class RegisterUser(CreateView): form_class = UserCreationForm template_name = 'users/register-user' def get(self, request, *args, **kwargs): return render(request, 'users/register-user.html', {'form': UserCreationForm()}) def post(self, request, *args, **kwargs): form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) messages.success(request, f'Welcome, {username}!') return redirect('cars') return render(request, 'users/register-user.html', {'form': form}) class ChangePassword(LoginRequiredMixin, CreateView): form_class = PasswordChangeForm template_name = 'users/change-password' def get(self, request, *args, **kwargs): form = PasswordChangeForm(request.user) return render(request, 'users/change-password.html', {'form': form}) def post(self, request, *args, **kwargs): form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) messages.success(request, 'Password changed!') return redirect('cars') return render(request, 'users/change-password.html', {'form': form}) it is my users urls:: from django.urls import path from users import views as users_views from django.contrib.auth import views as auth_views urlpatterns = [ path('', users_views.RegisterUser.as_view(), name='register_user'), path('change-password', users_views.ChangePassword.as_view(), name='change_password'), path('login', auth_views.LoginView.as_view(template_name='users/login.html'), name = 'login'), path('logout', auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'), ] it is my car views :: from .models import Car, Repair from django.views.generic … -
django: redirect user after generating the download of a template
I need to redirect a user after he finishes filling up a form and clicking on download, which generate a pdf template and then downloads it. I have tried redirecting from the backend side in django as well as in client side with javascript and nothing makes it. here is what I currently have: USER INPUT VIEW. (notice it redirects toward a template, which contains the pdf format.) def New_Sales(request): #context = {} form = modelformset_factory(historical_recent_data, fields=('id','Id', 'Description','Date','Quantity', 'NetAmount', 'customer_name', 'invoice_number')) if request.method == 'GET': formset = form(queryset= historical_recent_data.objects.none()) #blank_form = formset.empty_form elif request.method == 'POST': formset = form(request.POST) #invoice_hidden_form = CreateInvoiceForm(request.POST) #blank_form = formset.empty_form if formset.is_valid(): #request.session['sale'] = formset.cleaned_data for check_form in formset: check_form.save() quantity = check_form.cleaned_data.get('Quantity') id = check_form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity) request.session['sale'] = formset.cleaned_data #if invoice_hidden_form.is_valid(): #invoice_hidden_form.save() #print('invoice_hidden_form is saved successfully') #request.session['invoice'] = invoice_hidden_form.cleaned_data print(formset.cleaned_data) return redirect('/invoice/pdf/assembly/') PDF GENERATION + DOWNLOAD VIEW: def generate_pdf_assembly(request): data = request.session['sale'] invoice_number = data[0]['invoice_number'] print(data) #total_ht = request.session['sale'].get('NetAmount') rate_list = [] for index in range(len(data)): rate_list.append(round(data[index]['NetAmount']/data[index]['Quantity'],1)) total_ht = [] for index in range(len(data)): total_ht.append(data[index]['NetAmount']) print('total_ht', total_ht) total_ht = sum(total_ht) my_company = MyCompany.objects.get(id = 1) tva = … -
How to add an ImageField to the HTML and make it visible
I am trying make a proper ImageField so a user can change the image from the admin panel. But even know I see the image in the Media folder I still cannot see it on front page. setting.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = "/media/" model.py class HomePage(models.Model): name = models.CharField(max_length=10, blank=True) main_visual = models.ImageField(default="default.jpg", upload_to="homepage_pics") top_content_header = models.CharField(max_length=100, blank=True) top_content = models.TextField(max_length=100, blank=True) featured_groups_header = models.CharField(max_length=100, blank=True) featured_groups = models.TextField(max_length=100, blank=True) seven_groups_header = models.CharField(max_length=100, blank=True) seven_groups = models.TextField(max_length=100, blank=True) about_us_header = models.CharField(max_length=500, blank=True) about_us = models.TextField(max_length=500, blank=True) about_us_image = models.ImageField(default="about_us.png", upload_to="about_us_pics") def __str__(self): return f'{self.name}' views.py def home(request): if request.method == 'POST': form = ContactForm(request.POST or None) if form.is_valid(): sender_name = form.cleaned_data['name'] sender_email = form.cleaned_data['email'] message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message']) send_mail('New Enquiry', message, sender_email, ['warp.dev.group@gmail.com']) return HttpResponse('Thanks for contacting us!') else: form = ContactForm() context = { "homepage": HomePage.objects.filter(name="homepage").first(), "footer": Footer.objects.filter(name="footer").first(), 'form': form } return render(request, 'member/home.html', context) home.html <section class="site-section" id="about-section"> <div class="container"> <div class="row"> <div class="col-md-5 mr-auto"> <div class="text-left heading-wrap mb-5"> <h2 class="mt-0 mb-5">{{ homepage.about_us_header }}</h2> <p>{{ homepage.about_us }}</p> </div> </div> <div class="col-md-6 position-relative align-self-center"> <img src = {{ homepage.about_us_image }} alt="Image" class="img-overlap-1"> </div> </div> </div> </section> The about_us … -
Django ORM lookup syntax
I have a model Fruit, and fruit has orchards. class Fruit(): orchards = models.ManyToManyField('Orchard', blank=True) Each orchard belongs to a farm: class Orchard(): farm = models.ForeignKey('Farm', verbose_name='Farm', null=True, blank=True, on_delete=models.PROTECT) Every fruit is a seedling class Seedling(): fruit = models.ForeignKey('Fruit', editable=False, on_delete=models.CASCADE) Here is my attempt: queryset = Seedling.objects.all().filter(fruit__orchards__in__farm=farm_id) This gets me an error django.core.exceptions.FieldError: Related Field got invalid lookup: in Anyone able to clear up my query? Much appreciated -
Django CMS dinamically image
i need to change dinamically image background-image css from home page in django cms, but is imposible. home CSS CODE The css has the welcome-image-area class the user needs to change the image url in the cms. .welcome-area { height: 100%; } .welcome-image-area { position: relative; height: 100%; background-image: url(../images/bg/bg.jpg); background-size: cover; z-index: 1; } .welcome-image-area:after { position: absolute; background: rgba(0, 0, 0, .7); left: 0; top: 0; width: 100%; height: 100%; content: ""; z-index: -1; } HTML CODE base.html <div id="welcome-image-area" class="welcome-image-area" data-stellar-background-ratio="0.6" > <div class="display-table"> <div class="display-table-cell"> <div class="container"> <div class="row"> <div class="col-md-12 text-center"> <div class="header-text"> <h2>{% static_placeholder 'mensaje bienvenida' %}</h2> <p>{% static_placeholder 'sub mensaje bienvenida' %}</p> <a class="smoth-scroll hire-us-slide-btn" href="#service">Servicios <i class="fa fa-hand-pointer-o btn-hire-us" aria-hidden="true"></i></a> <a class="slide-btn smoth-scroll" href="#contact">Contactanos <i class="fa fa-hand-pointer-o btn-contact-us" aria-hidden="true"></i></a> </div> </div> </div> </div> </div> </div> </div> -
Why is my Django form not "valid"? Can't get the POST request to update database
I am trying to create a user profiles for users in my Django app. I have the form displaying where I want it to and when I try to submit, nothing happens. I put a print statement after the form.is_valid in my view.py and found that it wasn't 'valid' but I have no idea why. I have tried several different ways to 'clean' / 'validate' data but I can't get past the form being 'invalid.' Any help would be greatly appreciated! urls: path('userinfo/', views.user_info, name='userinfo') form template: {% extends "base.html" %} {% load bootstrap4 %} {% block content %} <div class="container"> <h1>Enter User Info</h1> <form method="POST" class="form"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" class="btn btn-primary" value="Create Profile"> </form> </div> {% endblock %} view: def user_info(request): form = ProfileForm() if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): form.save() else: form = ProfileForm() return render(request, 'miraDashboard/form.html', context={'form': form}) model: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) name = models.CharField("Full Name", max_length=1024) job_role = models.CharField("Role", max_length=254, default="Seeking Job Opportunities") zip_code = models.CharField("Zip Code", max_length=5) user_image = models.ImageField("Upload Profile Picture", upload_to='images/') def __str__(self): return f'{self.user.username} Profile' form: from django.forms import ModelForm from .models import … -
Trying to populate Django app database with Faker
I am trying to populate Django database with Faker. I created a Django project (name = first_project) and then I created a Django app (name = first_app). I created models in my app and then I created a file named 'populate_first_app.py' in my main first_project folder(the one which contains manage.py) and filled in with the following code: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings') import django django.setup() import random from first_app.models import Topic,Webpage,AccessRecord from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__ == '__main__': print("populating script!") populate(20) print("populating complete!") after making migrations and running the code, my terminal shows: (MyDjangoEnv) E:\Django\first_project>python populate_first_app.py populating script! Traceback (most recent call last): File "populate_first_app.py", line 34, in <module> populate(20) File "populate_first_app.py", line 28, in populate webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 573, in get_or_create return self.get(**kwargs), False File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 418, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File … -
nginx Error 502 upstream prematurely closed connection while reading response header from upstream
I've been banging my head on this issue for days now and have finally reached a brick wall. When i navigate to the page in the browser, the page with hang for a few seconds, before getting the 502 Bad Gateway Screen. Any ideas anyone??? url https://sv1.stream05.xyz/link/?driveId=0BwHxX3yoJoeuYzZlNm1jYVhwWWs According to NGINX logs, NGINX says: 2020/11/04 18:56:31 [error] 14920#14920: *15 upstream prematurely closed connection while reading response header from upstream, client: 141.101.84.6, server: sv1.stream05.xyz, request: "GET /link/?driveId=0BwHxX3yoJoeuYzZlNm1jYVhwWWs HTTP/1.1", upstream: "http://127.0.0.1:6868/link/?driveId=0BwHxX3yoJoeuYzZlNm1jYVhwWWs", host: "sv1.stream05.xyz" nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; upstream LoadBalancer { server 127.0.0.1:6666; } upstream ProxyStream { server 127.0.0.1:6868; } server { listen 80; server_name proxy.stream05.xyz; location / { proxy_pass http://LoadBalancer; proxy_http_version 1.1; proxy_send_timeout 600; proxy_read_timeout 600; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } … -
Django check form field attribute in template
I need to check if a form field is disabled in the template. The field is disabled depending on some other factors but I've simplified it below. class MyForm(forms.Form): quantity = forms.IntegerField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].disabled = True Then in the template I'd like to do something like this: {% if form.quantity.disabled is True %} ... {% endif %} -
How can I add a user to a predefined group on signup, using django and django-allauth?
I am using django-allauth. My users/formy.py contains this code: class CustomUserCreationForm(UserCreationForm): success_url = '/connections/' class Meta: model = User fields = ('email','password1') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self.fields['password2'] What do I need to modify to add the new user to a specific group, for example, a group called "basicuser"? -
import CSV as database Django
I'm trying to import data from a CSV file. I'm using this code: from django.db import models import csv # Create your models here. class Image(models.Model): name = models.IntegerField() # field - instance - row description = models.TextField(max_length=700) # field - instance - row mode = models.CharField(max_length=255) # field - instance - row celltype = models.CharField(max_length=255) # field - instance - row component = models.CharField(max_length=255) # field - instance - row doi = models.CharField(max_length=255) # field - instance - row organism = models.CharField(max_length=255) # field - instance - row def deleteAll(self): for img in self.objects.all(): img.delete() def ImportData(self): path = '/Users/macbookair/Downloads/source_project/images.csv' reader = csv.reader(open(path), delimiter=";", quotechar='"') next(reader) for row in reader: print(row) image = Image() image.name = row[1] image.description = row[2] image.mode = row[3] image.celltype = row[4] image.component = row[5] image.doi = row[6] image.organism = row[7] image.save() my CSV file looks like this: please click here But when I go to console to check my Image model, I find that it is empty! I'm checking this way: in console: python manage.py shell from myApp.models import Image image.objects.all() and I get: <QuerySet []> I already made the migrations using: python manage.py makemigrations myApp python manage.py migrate am I missing something? -
Django Locale not working after deploying to server
when i test it locally the translations do worked, but when I deploy it on a server it doesn't work. Some of the words do get translated but it's not from my locale, it's django's default translation. In settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'en-us' # LANGUAGE_CODE = 'zh-hans' # i also tried just putting language code as zh-hans but still ntg gets translated. TIME_ZONE = 'Asia/Kuala_Lumpur' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) For the LOCALE_PATHS it is correct as i put print(LOCALE_PATHS) in the settings and it gave me the right path to my locale "home/username/django_project/locale" I did do python manage.py makemessages -l zh_hans as well as python manage.py compilemessages and restarted my server but still the same. Btw I'm using AWS ubuntu and apache2. (Not apache problem as i tried python manage.py runserver 0.0.0.0:8000 before i even installed apache and it's still the same) My dev comp is windows and my server is ubuntu (not sure how it may help but yea) and there is no error at all there's just no translation. what could be the problem ? can … -
django display used template name in template
During development of projects with many model classes, views and forms, the wish to get the rendered template name, the used model class and form/view classes beeing displayed during template rendering in development mode arises. Is there a way to provide such information out of the box with the provided django toolbox ? This kind of information revealed during rendering of a template is only useful during development, of course, and should be disabled in production mode. -
When I try to start the Django server, the command line doesn't prompt anything
When I run python manage.py runserver it doesn't prompt anything. I don't get any errors, it just won't run. Does anyone know how to fix that? -
Django app on Nginx + Gunicorn. POST request failure - "500 Internal Server Error". Why?
I have a CentOS 7 VDS server with a Django app running on Nginx + Gunicorn setup. This application should be able to receive POST requests with medium size .docx files or large amount of text via textarea. And my problem is whenever I make POST request with files of any size OR with text larger than certain point (approx. 3/4 of A4 page) Nginx instantly throws 500 Internal Server Error. It does work with smaller texts in textarea just fine, though. I figured Nginx doesn't even send any request to Gunicorn server. Here's my nginx.conf file: worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; client_max_body_size 32M; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 10000; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; server { client_max_body_size 32M; listen 80; server_name mysite.com; #либо ip, либо доменное имя access_log /var/log/nginx/example.log; location = /favicon.ico { access_log off; log_not_found off;} location /static/ { root /somepath/myapp/; expires 30d; } … -
Is there another way to annotate Count/Sum in existing queryset?
Let me illustrate the problem with canonical models Book&Author. Here is the view: class Report(ListView): ... def get_queryset(self): ... # calculating of filters return Book.objects.filter(status='published', date= ... a bunch of filters) So that we have a queryset with all necessary filters. It might be used in another functions, for example, to get the number of books: def books_number(self): qs = self.get_queryset() return qs.count() or cost of all these books: def summa(self): qs = self.get_queryset() return qs.aggregate(Sum('price')) Now, I want to get number of books by each Author and their costs and I would be happy with something like this: def authors_info(self): qs = self.get_queryset() return Author.objects.annotate(books_number=Count( use qs somehow ... ), books_cost = Sum( use qs over field 'price' somehow ...) ) but I haven't yet found a way to do that. Well, to get it working I used this: def authors_info(self): ... # calculating of THE SAME filters AGAIN q_ = Q(status='published', date= ... a bunch of filters) count_ = Count('book', filter=q_) sum_ = Sum('book__price', filter=q_) return Author.objects.annotate(books_number=count_, books_cost=sum_) but it definitely contradicts with DRY principle. Is still there more tidy way to get queryset in one function and to annotate it in another function? -
Chatting app like facebook can make by Go language? [closed]
I want to make a chatting app like facebook but I have no idea about it like login and send, receive massages. -
How I LOGIN in other website through my form
I tring to post in https://login.microsoftonline.com/common/login with login and password directly from my website form like it: <form method="post" action="https://login.microsoftonline.com/common/login" enctype="multipart/form-data" target="_blank"> <div> <label>Choose a file</label> <input type="text" id="file" name="login"> </div> <div> <label >Choose a file</label> <input type="text" name="passwd"> </div> <div> <button>GO To Sharepont</button> </div> </form> But when I clik in the button return erro from microsoft is missing a TOKEN. How can I login in other site through my site form? -
Django allauth Sendgrid django error IncompleteRead(0 bytes read, 116 more expected)
I am using Django allauth to verify users after email however I keep getting the error: IncompleteRead(0 bytes read, 116 more expected) Currently, my view for the signup view for handling after post request is: if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): storage = messages.get_messages(request) for _ in storage: pass for _ in list(storage._loaded_messages): del storage._loaded_messages[0] user = form.save(commit=False) #user.is_active = False user.save() send_email_confirmation(request, user, True) return redirect('main:user_login') My Sendgrid settings is: SENDGRID_API_KEY = 'myaapikey' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'my username' EMAIL_HOST_PASSWORD = 'mypassword' DEFAULT_FROM_EMAIL = DEFAULT_EMAIL And my allauth is: AUTH_USER_MODEL = 'main.Profile' ACCOUNT_EMAIL_VERIFICATION='mandatory' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_EMAIL_REQUIRED= True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = False ACCOUNT_EMAIL_SUBJECT_PREFIX = "JoinCampus " SOCIALACCOUNT_ADAPTER = 'main.adapters.SocialAccountAdapter' When I use the Django Email backend the email is being sent however when I use Sendgrid it doesn't work. However, if I use sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) The emails are being send successfully. -
Redirect user to another form based on their response in the current form
My user is completing a sign up form. If they indicate that they are an 'expert'(choice field) in the form displayed using the SignUpView, I want them to be redirected to the ExpertInformationView, otherwise I want them to be redirected to my homepage. How can I do this? # views.py class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' class ExpertInformationView(FormView): template_name = 'info_form.html' form_class = ExpertUserInformationForm success_url = reverse_lazy('information') # models.py class CustomUser(AbstractUser): __USER_STATUS = [('Member', 'Member'), ('Expert', 'Expert')] user_status = models.CharField( max_length=20, choices=__USER_STATUS, default=__USER_STATUS[0], # 'Member' ) phone_number = models.CharField(null=True, blank=True, max_length=30) -
Is there a way to make a depend dropdown in django open edx registration?
i'm working in OpenEdx and i'm trying to make a registration page that contains custom fields, state and city. here is my models.py: class City(models.Model): name = models.CharField('city', max_length=100, blank=True) uf = models.CharField('UF', max_length=2, choices=STATE_CHOICES) def __str__(self): return self.name class Meta: ordering = ('name',) verbose_name = 'cidade' verbose_name_plural = 'cidades' class UserProfileExtras(models.Model): user = models.OneToOneField( USER_MODEL, null=True, on_delete=models.CASCADE ) state = models.CharField( verbose_name="State", choices=STATE_CHOICES, max_length=100, ) city = models.CharField( verbose_name="Cidade", choices=CITY_CHOICES, max_length=100, null=True, ) and forms.py: class UserProfileExtrasForm(ModelForm): class Meta(object): model = UserProfileExtras fields = ('state', 'city') def __init__(self, *args, **kwargs): super(UserProfileExtrasForm, self).__init__(*args, **kwargs) self.fields['state'].label = _(u"Estado") self.fields['state'].error_messages = { "required": _(u"Selecione seu Estado."), "invalid": _(u"Estado inválido."), } self.fields['city'].label = _(u"Cidade") self.fields['city'].error_messages = { "required": _(u"Selecione sua cidade."), "invalid": _(u"Cidade inválida"), } i want to make the city dropdown appears only the selected state's cities thanks -
The QuerySet value for an exact lookup must be limited to one result
hello guys iam having issue in the underlying section as iam tring to print this comment section my models.py file iam trying to get the detailed page of any single post which contains post and comment form and previous comments but i am getting this errorThe QuerySet value for an exact lookup must be limited to one result using slicing. from django.db import models class Category(models.Model): name=models.CharField(max_length=60) def __str__(self): return self.name class Post(models.Model): title=models.CharField(max_length=60) body=models.CharField(max_length=500) created_on = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) categories = models.ManyToManyField('Category', related_name='posts') def __str__(self): return self.title class Comment(models.Model): author = models.CharField(max_length=60) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) post = models.ForeignKey('Post', on_delete=models.CASCADE) def __str__(self): return self.body And my views.py file is from django.shortcuts import render from django.http import HttpResponse from .models import * from .form import CommentForm def blog_index(request): post=Post.objects.all().order_by('created_on') context={ 'post':post } return render(request,'blog/blog_index.html',context) def blog_detail(request,id): posts = Post.objects.filter(categories__name__contains=category).order_by('-created_on') form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment( author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=posts ) comment.save() comments = Comment.objects.filter(post=posts) context = { "post": posts, "comments": comments, "form": form, } return render(request, "blog/blog_details.html", context) def category(request,Category): posts = Post.objects.filter(categories__name__contains=category).order_by('-created_on') context = { "category": category, "posts": posts } return render(request, "blog/blog_category.html", context)