Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting "Error processing tar file(exit status 1): open /myenv/include/python3.6m/Python-ast.h: no such file or directory" while docker-compose build
So I am pretty new to docker and django. Unfortunately while running the below command on my linux machine which i am connected using my physical windows machine using putty: docker-compose build I am getting an error: Error processing tar file(exit status 1): open /myenv/include/python3.6m/Python-ast.h: no such file or directory 'myenv' is the environment I have created inside my folder. I am getting a container started on port 9000. The app doesn't have anything yet just a simple project so i just expect to see the 'congratulations' screen. I don't know where I am going wrong. My final goal would be to run the docker url in my windows browser and see the screen of docker container. This is my docker-compose.yml file: version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:9000 ports: - 202.179.92.106:8000:9000 the IP: 202.179.92.106 is my public IP. I did the above binding so as to access the docker container from my windows machine. Would request additional inputs for the port binding as well if correct/incorrect. Below is my Dockerfile: FROM python:3.6.9 RUN mkdir djangotest WORKDIR djangotest ADD . /djangotest RUN pip install -r requirements.txt Please help me out peeps! -
How to pass a JSON data from a form in ReactJS to Django View inside of a variable?
I want to receive data from a Reactjs frontend form (JSON format) into my django view, where the json data would be stored inside of a variable, which then later i could insert into bigquery using the insert_rows_json method. Is it possible? Thanks in advance cheers! -
field_name = ordering[0].lstrip('-') throws IndexError: tuple index out of range in DRF rest_framework\pagination.py
I am getting error IndexError: tuple index out of range while using CursorPagination of DRF. my code- class CursorSetPagination(CursorPagination): page_size = 10 page_size_query_param = 'page_size' ordering = '-created_at' class WalletCreditViewset(viewsets.ReadOnlyModelViewSet): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] pagination_class = CursorSetPagination serializer_class = WalletCreditSerializer def get_queryset(self): queryset = PaymentOrder.objects.filter(user=self.request.user) return queryset The errors comes when the entry in the database table for a particular user cross the value of page_size. Ex- if some user have 5 payment order then there will be no error but when the same user cross 10 payment order then this error occurs. -
How can I upload new webpages to a django app?
I am quite new to django so I am sorry if I have overlooked something simple. This is my current website: https://www.michealnestor.com I am trying to remake it using react and django, and a lot of it is different, however I want to keep the functionality of being able to run my js apps from the website: https://www.michealnestor.com/projects EXAMPLE: https://www.michealnestor.com/projects/sortingalgorithms/ . I want to be able to upload project folders, with html, css and js in them from the admin page, and then be able to open these projects from my website. I am not sure how to do this though. I have tried manually placing such a folder in a templates folder in my app, and I have managed to use a view to load the html file, but this file can't seem to find the css and js. Maybe I am going about this the wrong way, in any case I would appreciate some guidance! -
I want to make social registration without token validation
When registering via google or facebook, this code checks it with the user token, I want to make sure that the code does not check it and can register and save any user even if its token is not correct GOOGLE_CLIENT_ID is google accounts secret code SOCIAL_SECRET is facebook accounts secret code a long id token comes to auut_token which I take from https://www.googleapis.com/auth/userinfo.email, but I need to be able to enter any token in the field and it will register it anyway. I would really appreciate your help My serializers.py from rest_framework import serializers from . import google, facebook from .register import register_social_user import os from rest_framework.exceptions import AuthenticationFailed class FacebookSocialAuthSerializer(serializers.Serializer): """Handles serialization of facebook related data""" auth_token = serializers.CharField() login = serializers.CharField() def validate_auth_token(self, auth_token): user_data = facebook.Facebook.validate(auth_token) try: user_id = user_data['id'] email = user_data['email'] first_name = user_data['first_name'] provider = 'facebook' return register_social_user( provider=provider, user_id=user_id, email=email, first_name=first_name ) except Exception as identifier: raise serializers.ValidationError( 'The token is invalid or expired. Please login again.' ) class GoogleSocialAuthSerializer(serializers.Serializer, ): auth_token = serializers.CharField() email = serializers.EmailField def validate_auth_token(self, auth_token): user_data = google.Google.validate(auth_token) try: user_data['sub'] print(user_data['sub']) except: raise serializers.ValidationError( 'The token is invalid or expired. Please login again.' ) from phrasebook.settings import … -
About innerHTML can't display pictures
The text can be displayed normally. Here is my code: <div id='container'> </div> <script> document.getElementById("container").innerHTML = "{{ article.content }}"; </script> The result appears like this on the web page: <p>&nbsp; &nbsp; detail: x_1 1</p><p style="text-align: center;"><img src="/media/uploads/images/xx_20210827151909_960.jpg" alt="xx.jpg" width="1137" height="710" style="width: 1137px; height: 710px;"/></p> They are not displayed as web page elements. (The path of the img src is right. I use: return render(request, 'news/article.html',{'article': article,'username':username}) to return article, article is the object returned by article.objects.get (PK = PK). content is an attribute of article.) -
Django Download zip file containing multiple url content with images
i have following code class getData(APIView): permission_classes = [AllowAny] file_loc = "csv/1 პრიორიტეტი - 1 პრიორიტეტი.csv" def get(self, request, *args, **kwargs): data = {} with open(self.file_loc, 'r', newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: code = row['ISBN'] url = row['ყდის ფაილი'] data[code] = url file2 = open(self.file_loc) reader = csv.reader(file2) lines = len(list(reader)) some = 0 while some != lines: for k,v in data.items(): print(k, 'Da', v) response = HttpResponse( content=requests.get(v).content, content_type='image/jpeg', headers={"Content-Disposition": "attachment; filename={}".format(k+'.jpg')}, ) some+=1 return response with the following code i have keys and values for dictionary data, keys are image names and values are url of image. all im trying to do is when someone sends get request to that value(url), download all images with keys(imageNames). the problem i have is it send only one response and dont go through data items the best solution would be save those images with its names to hard drive and on GET request download zip file containing all the data. any ideas? -
Django smtp connection with office 365 Outlook
We are receiving the following error using the Office 365 SMTP server to send mails from the Django application. smtplib.SMTPAuthenticationError: 535, b'5.7.139 Authentication unsuccessful, the request did not meet the criteria to be authenticated successfully. Contact your administrator. [PN2PR01CA0065.INDPRD01.PROD.OUTLOOK.COM]' following setup did in the Django setting.py EMAIL_HOST=smtp.office365.com EMAIL_USE_TLS=True EMAIL_PORT=587 # also tried port 25 EMAIL_USER=test@example.com EMAIL_PASSWORD=test And following the steps for setting up the Outlook 365 SMTP relay account (Steps) and also checked the Authenticated SMTP for the admin account. -
nslookup from csv in django and display ip address on webapp
web app to nslookup from 1 csv and display their ip address on the page the table should contain id location website ip address other ip address port 1 page should also nslookup individual ip address of hostname entered by user -
how can I install django website on localhost with bash export
I'm new to django programming, I have downloaded the discord website from git hub https://github.com/python-discord/site. I am trying to install this website for the last 5-6 hours. I searched for an answer everywhere, unfortunately I can't find a clear answer. I will write my steps so far: Downloaded the source code Started venv, started new project and then copied all files to the folder. Added conf folder and inside secret.json now i am stuck at 4: Add export DJANGOPROJECT_DATA_DIR=~/.djangoproject (without the backticks) to your ~/.bashrc (or ~/.zshrc if you're using zsh, ~/.bash_profile if you're on macOS and using bash) file and then run source ~/.bashrc (or source ~/.zshrc, or source ~/.bash_profile) to load the changes. I added the line: export DJANGOPROJECT_DATA_DIR=~/Desktop/website/site-main (this is my website folder path) at the end of the .bashrc file. But I get nothing beside: 'source' is not recognized as an internal or external command, operable program or batch file. I changed the command to set for windows but nothing happen. enter image description here raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable -
Migration not being created in database
I connected my app to my database in my settings.py and then ran migrations and my model 0001_initial.py file was created but when i try to apply those migrations to the database and create a table it says no migrations to apply and it doesn't create the table. I dont know why Machine 0001_initial.py class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Appear', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('Show', models.CharField(max_length=100)), ('Media', models.CharField(blank=True, choices=[('TV', 'TV'), ('Radio', 'Radio'), ('Youtube', 'Youtube'), ('Podcast', 'Podcast')], max_length=30, null=True)), ('Episode', models.IntegerField()), ('Date', models.DateField(max_length=100)), ('Time', models.TimeField()), ('Producer', models.CharField(max_length=100)), ('Producer_Email', models.EmailField(max_length=254)), ], ), ] why is the table not being created. -
Django ModelForm not getting instance data
I have a model form that have multiple choice fields. using AJAX to update form choic fields upon changed field. Model: class Student(models.Model): CLASSROOM = 0 GROUPROOM = 1 HOMEROOM = 3 STUDENT_RECORD_TYPES = [ (CLASSROOM,_("Classroom")), (GROUPROOM,_("Group")), (HOMEROOM,_("Home Edu")), ] school = models.ForeignKey(School,on_delete=models.CASCADE,blank=False,related_name='student_records') grade = models.ForeignKey(Grade,on_delete=models.CASCADE,blank=False,related_name="student_records") record_type = models.PositiveSmallIntegerField(_("Record Type"),choices=STUDENT_RECORD_TYPES,default=0) class Meta: constraints = [ models.UniqueConstraint( fields=['school','grade', 'record_type'], name='unique_school_grade_record' ), ] def __str__(self): return "Record ID: {}".format(self.pk) Views.py: def update_students(request,pk): updated_table=None student_record = get_object_or_404(Student,pk=pk) if request.POST: form = StudentForm(request.POST or None,instance=student_record) if form.is_valid(): form.save() messages.success(request,_("Student record Updated Successfully!")) #Getting data for view updated_table = update_students_table(request) else: messages.error(request,_("Invalid Input, Please check!")) else: form = StudentForm(request.GET or None,instance=student_record) context = {} # load form template context['form'] = form form_template_path = "components/forms/student_update.html" html_form = loader.render_to_string(form_template_path, context, request) context['form'] = html_form return JsonResponse(context) Forms.py: class StudentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StudentForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' self.fields['school'].widget.attrs['class'] += ' select2' #the issue stands here #self.data.get('school') returns none even if its exist in form data if self.data.get('school'): self.fields['grade'].queryset = Grade.objects.filter(school=self.data.get('school')) else: self.fields['grade'].queryset = Grade.objects.none() class Meta: model = Student fields = '__all__' the strange behavior drives me crazy because when I reselect the school it updates the grade choices normally (with … -
Adding values to a cell in a table, depending on the model
I have in models.py class Product(models.Model): class Meta: abstract = True name = models.CharField(max_length=250) cost = models.IntegerField() class CPU(Product): SOCKETS = ( ( 'AMD', ( ('AM3', 'Socket AM3'), ('AM3+', 'Socket AM3'), ('AM4', 'Socket AM4'), ('TR4', 'Socket TR4'), )), ('Intel', ( ('1336', 'Socket 1336'), ('1156', 'Socket 1156'), ('1155', 'Socket 1155'), ('2011', 'Socket 2011'), ('1356', 'Socket 1356'), ('1150', 'Socket 1150'), ('2011-3','Socket 2011-3'), ('1151', 'Socket 1151'), ('1151v2', 'Socket 1151v2'), ('2066', 'Socket 2066'), ('1200', 'Socket 1200'), )) ) sockets = models.CharField(max_length = 6, choices = SOCKETS, blank = True) def __str__(self): return self.name class Motheboard(Product): FACTOR = ( ('MicATX','Micro-ATX'), ('MinATX','Mini-ATX'), ('FATX','FlexATX'), ('ATX','ATX'), ('minITX','mini-ITX'), ('minDTX','mini-DTX'), ('eATX', 'Extended ATX'), ) company = models.CharField(max_length = 80) form_factor = models.CharField(max_length = 6, choices = FACTOR, blank = True) def __str__(self): return self.name and in table.py class Meta: model = Product fields = ("name", "cost") I want to achieve something like this: | Name | Cost | |------|------| | Ryzen 5 Socket AM4|30| | ASROCK B460M Micro-ATX |25| How can I make the fields of child models appear in the cells with the name? Is it possible to do this in django tables or do you need to create your own fields in the database? Thanks! -
Class View vs def view Django
Hello I have a simply question about Django Web Framework. I am curious what should i use. Function view or class view and try to change all the function views to the class view? What are differences cons and pros? -
Retrieve all related objects of objects in a queryset
Asked another question yesterday. Unfortunately, the answer did not solve the problem so I thought I narrow the question down and ask again. I have a Category model which is hierarchial(using django-treebeard). When I run example_category.get_descendants() the result I get is a MP_NodeQuerySet like the following <MP_NodeQuerySet [<Category: shoes>, <Category: Sneakers>, <Category: laced_sneakers>]> Out of this queryset I want to fetch every product related to each category and display in a view(DetailView). My best bet has been def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["products_in_category"] = Category.objects.prefetch_related( Prefetch("products", queryset=self.object.get_descendants())) return context Which results in the error "Cannot resolve keyword 'category' into field. Choices are: depth, description, id, numchild, path, products, slug, title" I guess I for some reason get the category back and not its products and I don't really know how to solve it. Check out the old question for more context or just ask away! -
Simple django filter is includes all users’ data rather than that of the logged-in user
I’m new to Django and have built a basic filter that does not filter according to the logged-in user’s data but rather all users’ data, which is incorrect. The filter is for an Automation class, which has a many:many relationship with the Message class (and funnily enough the exact same happens with the message filter). Views.py: @login_required(login_url='login') @allowed_users(allowed_roles=['admin', 'customer'], own_account_only=True) def automation_list(request, pk): account = Account.objects.get(id=pk) automations = account.automation_set.all() filter = AutomationFilter(request.GET, queryset=automations) automations = filter.qs context = {'account': account, 'automations': automations, 'filter': filter} return render(request, 'automations/automation_list.html', context) Filters.py: class AutomationFilter(django_filters.FilterSet): start_date = DateFilter(field_name='date_joined', lookup_expr='gte') end_date = DateFilter(field_name='date_joined', lookup_expr='lte') class Meta: model = Automation fields = '__all__' exclude = ['account', 'date_created'] Models: class Automation(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=200) account = models.ForeignKey(Account, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) messages = models.ManyToManyField(Message, blank=True) def __str__(self): return self.name class Message(models.Model): name = models.CharField(max_length=100) subject = models.CharField(max_length=128) text = models.TextField() account = models.ForeignKey(Account, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) automations = models.ManyToManyField('automations.Automation', blank=True) def __str__(self): return self.name Why is the filter not just filtering according to the logged-in user? I’d have thought that I’m only passing in the user’s data via this line: filter = AutomationFilter(request.GET, queryset=automations) Thanks -
Getting 504 Gateway Time-out for Django on Ubuntu
I deployed a Django app on Ubuntu 20.04 with Digital Ocean. The app has a Python package called howdoi that does some web scraping of google search results. I upgraded howdoi with pip from 2.0.16 to 2.0.17. Once I did that, the website stopped working and shows this error: 504 Gateway Time-out nginx/1.18.0 (Ubuntu) But if I downgrade the package to 2.0.16 the website works. The issue only happens on the production server. On localhost, the web app works fine. I am not sure what is the correct command to see the errors. I tried this command: sudo journalctl -u gunicorn -f and that returns these logs (I removed UTC times from the logs to make them more readable here): Aug 27 11:00:05 django-s-1vcpu-2gb-nyc1-01 gunicorn[469603]:[INFO] Worker exiting (pid: 469603) Aug 27 11:00:06 django-s-1vcpu-2gb-nyc1-01 gunicorn[469545]:[WARNING] Worker with pid 469603 was terminated due to signal 9 Aug 27 11:00:06 django-s-1vcpu-2gb-nyc1-01 gunicorn[469665]:[INFO] Booting worker with pid: 469665 Aug 27 11:08:10 django-s-1vcpu-2gb-nyc1-01 gunicorn[469545]:[CRITICAL] WORKER TIMEOUT (pid:469665) Aug 27 11:08:10 django-s-1vcpu-2gb-nyc1-01 gunicorn[469665]:[INFO] Worker exiting (pid: 469665) Aug 27 11:08:11 django-s-1vcpu-2gb-nyc1-01 gunicorn[469545]:[WARNING] Worker with pid 469665 was terminated due to signal 9 Aug 27 11:08:11 django-s-1vcpu-2gb-nyc1-01 gunicorn[469920]:[INFO] Booting worker with pid: 469920 I also tried this: … -
Hot to make a user profile view?
Since I am new to django, this is my first time trying to create a user profile. And I don't know how to make a profile view with a link to it. Could you please give me an example models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length = 40, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) slug = AutoSlugField(populate_from = 'username', null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() class Meta: verbose_name = 'Пользователь' verbose_name_plural = 'Пользователи' def __str__(self): return self.email def get_absolute_url(self): return reverse('profile', args=[str(self.slug)]) class UserProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete = models.CASCADE, null = True, db_constraint=False) avatar = ProcessedImageField( upload_to = 'avatar', format = "JPEG", default = "avatar/empty_avatar.jpg", processors = [ResizeToFit(250, 200)], options = {'quality': 90}, blank = True, null = True, ) description = models.TextField(default = '', blank = True, null = True) slug = AutoSlugField(populate_from = 'user', null=True) class Meta: verbose_name = 'Профиль' verbose_name_plural = 'Профили' @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=CustomUser) def save_user_profile(sender, instance, **kwargs): try: instance.userprofile.save() except ObjectDoesNotExist: UserProfile.objects.create(user=instance) forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email', 'username',) class CustomUserChangeForm(UserChangeForm): class Meta: model = get_user_model() fields … -
Django / DRF - Invalid syntax in a Response object
everyone. Sorry for dumb question. I follow this guide: https://www.youtube.com/watch?v=4Uy8NZsUfF0&t=3341s&ab_channel=JayCoding Here I have a Response object: https://youtu.be/4Uy8NZsUfF0?t=3352 return Response('test': self.get_serializer(test, context={'request': self.request}).data, 'last_question_id':last_question) And I get "Invalid syntax" on colons. But in video it works. When I change string to this: return Response(self.get_serializer(test, context={'request': self.request}).data, last_question) It works well. What should I change to make it work? Thank you. -
Persistent slug in Django
In my Django web application, each user has a randomly generated token generated for purposes beyond the scope of this question. This is the relevant Profile model models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,max_length=30) verified_account = models.BooleanField(default=False) verify_token = models.SlugField(max_length=15, blank=True, null=True, unique=True) def __str__(self): return self.user.username def get_absolute_url(self): return reverse('user:profile', kwargs={'pk': self.pk}) def generate_token(self): #important from django.utils.crypto import get_random_string self.verify_token = get_random_string(length=15) return self.verify_token def save(self, *args, **kwargs): # also important self.slug = slugify(self.user.username) self.generate_token() # issue is here super().save(*args, **kwargs) So basically, whenever a Profile object is created (on the creation of the User model), a token is randomly generated. However, whenever the Profile model is updated, so is the verify_token. Below is the code for my @receiver that handles user creation @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) else: instance.profile.save() I have tried to insert the following code below the Profile.objects.create(user=instance) line in order to try and get it to only generate the token when the Profile is created Profile.objects.filter(user=instance).generate_token() But this gives me the following error 'QuerySet' object has no attribute 'generate_token' What is the best way to ensure that the slug is not changed after every update of it's Profile model? Thank … -
AttributeError: 'NoneType' object has no attribute 'nace_classes'
Hej! I get an the Error: AttributeError: 'NoneType' object has no attribute 'attribute'. There error occurs when I try to save an institution in the django admin area. All other fields work totally fine. The function where I get the error is a @classmethod in my models.py # class StringFactory: @classmethod def construct_string(cls, something) value = set() value2 = set() for klass in something.attribute.all() # here is the error value.add(klass.code_str()) value2.add(klass.some_str()) return " ,".join(value) if I print my something it is None. Therefor the NoneType error. I am new to classes and classmethods. Can anyone help me where I should look whats going wrong and why it can't find my 'something' or why it is None? I call the class in a function in another class in a django admin.py So I guess the error comes from there. # class SomethingForm(forms.ModelForm): def construct_initial_string(self, somethingelse): return StringFactory.construct_string(somethingelse) I am a bit lost with the classes and tried to name all given somethings (something, somethingelse) the same, but nothing changed. If you want I can post more code but it's very much and in different files. Thanks for your help! -
bcrypt return TypeError Unicode-objects must be encoded before checking
I am trying to create login and Signup using django. All the database are stored in MySql. def signup(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username and password: Myobject = adminUser() Myobject.username = username Myobject.password = bcrypt.hashpw(password.encode('utf8'),bcrypt.gensalt()) Myobject.save() print("User Created Successfully") else: messages.WARNING("Username and Password can not be blank") return render(request,'signup.html') Using this signup function I am able to stored the username and hashed password in database. if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username is not None and password is not None: user=adminUser.objects.get(username=username) hashed_password = user.password is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password) print(is_check) return render(request,'login.html') During the login, I am getting this TypeError. I have already encoded the password. -
Outputting database items to a pdf document
I have currently generated a Trial Balance with Pastel Database items on a web page as per the below image. I need to add a button that will be able to download the exact same thing onto a pdf document. trb.html: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous"> {% extends "main/base.html"%} {% block content%} <h1>Kyle Database Trial Balance</h1> <br> <br> <div class="container"> <div class="row mb-0"> <div class="col"> <h3>Account</h3> <br> {% for accountNo in accountNo %} <p style="font-size:10px">{{ accountNo }}</p> {% endfor %} <br> <b><p style='font-size:11px' style='font'>Totals</p></b> </div> <div class="col-5"> <h3>Description</h3> <br> {% for description in description %} <p style="font-size:10px">{{ description }}</p> {% endfor %} </div> <div class="col"> <h3>Debit</h3> <br> {% for debit in debit %} <p style="font-size:10px">{{ debit }}</p> {% endfor %} <br> <b><p style="font-size:11px">{{ totalDebit }}</p></b> </div> <div class="col"> <h3>Credit</h3> <br> {% for credit in credit %} <p style="font-size:10px">{{ credit }}</p> {% endfor %} <br> <b><p style="font-size:11px">{{ totalCredit }}</p></b> </div> </div> </div> {% endblock %} Views.py: def Kyletrb(request): desc = "SELECT Description FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" cursor = cnxn.cursor(); cursor.execute(desc); description = [tup[0] for tup in cursor.fetchall()] accNo = "SELECT Account FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" cursor.execute(accNo); accountNo = [tup[0] for tup in cursor.fetchall()] deb = "SELECT Debit … -
Django Heroku Channels Live Chat Fail
I've deployed my app on Heroku and everything works fine EXCEPT the live chat (used websockets for this). I'm not sure what is going on. The live chat feature works perfectly fine in development. I have not setup the postgres database or AWS S3 yet for file storage, but that doesn't have much to do with why the chat isn't working I suppose. Here are my files related to heroku and the live chat: settings.py: CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } Profile: web: gunicorn reddix.wsgi --log-file - There is an error that says I need to use wss (it doesn't say this if I use http) so I already how to fix that issue. The bigger issue is that the live chat does not work on either ws/http or wss/https. It keeps saying: WebSocket connection to 'ws://myapp-test.herokuapp.com/pathtochat/' failed Here are my requirements.txt: aioredis==1.3.1 asgi-redis==1.4.3 asgiref==3.4.1 async-timeout==3.0.1 attrs==21.2.0 autobahn==21.3.1 Automat==20.2.0 backports.entry-points-selectable==1.1.0 bleach==4.0.0 boto3==1.18.30 botocore==1.21.30 cffi==1.14.6 channels==3.0.4 channels-redis==3.3.0 constantly==15.1.0 cryptography==3.4.8 daphne==3.0.2 distlib==0.3.2 Django==3.2.6 django-bleach==0.7.2 django-ckeditor==6.1.0 django-cleanup==5.2.0 django-crispy-forms==1.12.0 django-js-asset==1.2.2 django-model-utils==4.1.1 django-notifications-hq==1.6.0 django-storages==1.11.1 djangorestframework==3.12.4 filelock==3.0.12 gunicorn==20.1.0 hiredis==2.0.0 hyperlink==21.0.0 idna==3.2 incremental==21.3.0 jmespath==0.10.0 jsonfield==3.1.0 msgpack==1.0.2 msgpack-python==0.5.6 packaging==21.0 Pillow==8.3.1 platformdirs==2.2.0 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.20 pyOpenSSL==20.0.1 pyparsing==2.4.7 python-dateutil==2.8.2 python-decouple==3.4 pytz==2021.1 redis==2.10.6 s3transfer==0.5.0 service-identity==21.1.0 six==1.16.0 sqlparse==0.4.1 swapper==1.1.2.post1 … -
The form validation returning False in Django
views.py def student_login(request): form = StudentLoginForm() if request.method == 'POST': form = StudentLoginForm(data=request.POST) print(form.is_valid()) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') print(username) user = authenticate(username=username,password=password) if user is not None: login(request,user) return redirect('index') else: messages.error(request,'Invalid username or password!') else: messages.error(request,'Invalid username or password!') context = {'form':form} return render(request,'student_login.html',context) models.py class Student(models.Model): name = models.CharField(max_length=100) username = models.CharField(max_length=100,unique=True,default=None) mobile = models.CharField(max_length=8) email = models.CharField(max_length=200,unique=True) password = models.CharField(max_length=200,default=None,unique=True) total_books_due = models.IntegerField(default=0) def __str__(self): return self.name forms.py class StudentLoginForm(forms.ModelForm): class Meta: model = Student fields = ['username','password'] widgets = { 'password':forms.PasswordInput(), } student_login.html {% extends 'base.html' %} <!-- {% load crispy_forms_tags %} --> {% block content %} <div class="container"> <br> <h2>Student Login Form</h2> <br> <form method="POST" action=""> {% csrf_token %} {% if messages %} {% for message in messages %} <div class="alert alert-danger" role="alert"> {{ message }} </div> {% endfor %} {% endif %} <br> {% for field in form %} <p>{{ field.label }} </p> <p>{{ field }} </p> <br> {% endfor %} <br> <input type="submit" class="btn btn-primary" value="Login"> </form> </div> {% endblock %} I have been trying to change again and again but form.is_valid() is still returning False. I could not figure out the reason that the form is not valid …