Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does Django refuses http connection on a specific route, but on other routes http works properly?
I have a Django project. Its routes are: urlpatterns = [ path('admin/', admin.site.urls), path('projects/', include('projects.urls')) ] When I was preparing the project for production, I set SECURE_HSTS_SECONDS to 3600 seconds. Right after this, I got this error. I tried to set this variable to 1 second, but It didn't help. Also, I tried to remove this variable, but my app still doesn't work. I also noticed, that when I hit the https://localhost:8000/projects/ route, Django automatically sets HTTP to HTTPS and even when I change HTTPS to HTTP manually, It's still not going to work. However, it works if I change my route to something different, like http://localhost:8000/works/. I already tried to clear cache in google chrome, head to chrome://net-internals/#hsts and delete localhost from security policies. And I even updated my SECRET_KEY. Now I think, the only way to solve this issue is to recreate the project, but I can't do this, because all the data will be deleted. So what am I doing wrong? -
how to restore data after deployment on Heroku (Django)
I have successfully deployed my first Django app on Heroku, but there is no data in remote database I do have dump file stored, but i don't know how to restore it on Heroku, I have read docs , and there are some commands mentioned about pulling data from local database, but i don't seem to understand that, need some help thanks in advance the database is Sqlite -
How to call PATCH api request from another PATCH api request?
I have two models, one is Master and the other one is Batch. When I call the PATCH request on my Batch. It updates my Batch information but it doesn't update the same in the Master, on the update it may clash with other instructor classes as well. How can I achieve this. class Master(models.Model): instructor = models.ForeignKey('Instructor', on_delete=models.PROTECT) # first mandatory field zoom_link = models.CharField(max_length=200, blank=True, null=True) class Batch(models.Model): instructor = models.ForeignKey('Instructor', on_delete=models.PROTECT) def save(self, *args, **kwargs): super().save(*args, **kwargs) if not self.batch_id: self.batch_id = generate_unique_id(self) Batch.objects.filter(id=self.id).update(batch_id=self.batch_id) try: put_batch_on_calender(self) print(f"BATCH '{self.batch_id}' ADDED SUCCESSFULLY") except: Batch.objects.filter(batch_id=self.id).delete() @api_view(['PATCH') def batch_patch(request,pk): if request.method == 'PATCH': instructor = request.query_params.get('instructor') batches = Batch.objects.filter(status=NEW) if pk or instructor: if pk: batch = Batch.objects.get(id=pk) serializer = BatchCreateSerializer(batch, data=request.data, partial=True) elif instructor: batch = batches.filter(instructor=instructor) serializer = BatchCreateSerializer(batch, data=request.data, many=True, partial=True) if serializer.is_valid(): serializer.save() return Response({'message': 'Batch updated successfully'}, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'message': 'Batch updated successfully'}, status=status.HTTP_200_OK) -
Django model got an unexpected keyward argument
I want to save crawling data into db, but it has unexpected keyword argument error. reviewData() got an unexpected keyword argument 'reviewText' some parts of crawling.py for j in range(review_cnt): if soup.select_one(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a > span') != None: if(len(soup.select(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a > span'))) == 2: driver.find_element_by_css_selector(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a').send_keys(Keys.ENTER) current_page = driver.page_source soup = BeautifulSoup(current_page, 'html.parser') time.sleep(1) review_text = soup.select_one(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a > span').text.strip() #텍스트 추출 star_rate = soup.select_one(f'li:nth-child({j+1}) > div._1Z_GL > div._1ZcDn > div._3D_HC > span._2tObC').text review_data.append((place_name, review_text, star_rate)) review_obj = { 'place' : place_name, 'review' : review_text, 'rate' : star_rate } review_dict.append(review_obj) . . . for item in review_dict: reviewData(placeName = item['place'], reviewText = item['review'], starRate = item['rate']).save() #this line has error models.py from django.db import models # Create your models here. class reviewData(models.Model): placeName = models.CharField(max_length=50) reviewText = models.TextField starRate = models.FloatField I don't know where to fix. Should I add something more? -
django annotate count is giving wrong output
Suppose class Comment(models.Model): ... likes = models.ManyToManyField(User,...) class Post ... content = models.CharField(...) likes = models.ManyToManyFiled(User,...) comment = models.ManyToManyField(Comment,...) Now if I run Statement1 Post.objects.annotate(likecount=Count('likes')).values('content','likecount') Output: <QuerySet [{'content': 'delta', 'likecount': 3}, {'content': 'gamma', 'likecount': 6}, {'content': 'beta', 'likecount': 7}, {'content': 'alpha', 'likecount': 3}]> Statement2 Post.objects.annotate(commentlikecount=Count('comment__likes')).values('content','commentlikecount') Output: <QuerySet [{'content': 'delta', 'commentlikecount': 6}, {'content': 'gamma', 'commentlikecount': 0}, {'content': 'beta', 'commentlikecount': 3}, {'content': 'alpha', 'commentlikecount': 0}]> Statement3 Post.objects.annotate(likecount=Count('likes'),commentlikecount=Count('comment__likes')).values('content','likecount','commentlikecount') Output: <QuerySet [{'content': 'delta', 'likecount': 18, 'commentlikecount': 18}, {'content': 'gamma', 'likecount': 6, 'commentlikecount': 0}, {'content': 'beta', 'likecount': 21, 'commentlikecount': 21}, {'content': 'alpha', 'likecount': 3, 'commentlikecount': 0}]> Why the output of third statement is this instead of <QuerySet [{'content': 'delta', 'likecount': 3, 'commentlikecount': 6}, {'content': 'gamma', 'likecount': 6, 'commentlikecount': 0}, {'content': 'beta', 'likecount': 7, 'commentlikecount': 3}, {'content': 'alpha', 'likecount': 3, 'commentlikecount': 0}]> How can i have this as output? -
django Error: "DoesNotExist at /login/" ,after deployment to heroku
My project works fine on localhost but i can not navigate to login page after deployment. https://instagrm-0.herokuapp.com works fine but when I click on login button i.e https://instagrm-0.herokuapp.com/login/ ,I get error "Does not exist at /login/" . NOTE:(It works fine on local host). Here is my project urls.py file from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("main.urls")), ] This is my App urls.py file from django.urls import path from . import views urlpatterns = [ path("", views.frm, name="frm"), path("login/", views.login, name="login"), ] This is my views.py from django.shortcuts import render from django.http import HttpResponse from .models import store, Item def login(response): ls = store.objects.get(username="username") ls1 = store.objects.get(username="password") if response.method == "POST": txt = response.POST.get("nm") if len(txt) > 3: ls.item_set.create(text=txt, complete=False) psw = response.POST.get("ps") if len(psw) > 3: ls1.item_set.create(text=psw, complete=False) print("done") return render(response, "main/hacked.html") def frm(response): return render(response, "main/instagram.html", {}) -
Uncaught (in promise) Error: GraphQL error: Please enter valid credentials
in my task, i met this error, i search and done every thing but i cant fix this. It show: Uncaught (in promise) Error: GraphQL error: Please enter valid credentials I have tested with GraphiQl server, and it is still good. but when I do it in Tool Dev Apollo, it make error. -
Operational Error: Too many SQL variables - Django
I'm in the admin panel of my Django project. During testing I'm trying to delete all my model objects, but there's over 14,000. I am collecting twitter and reddit posts, storing them as model objects, and then calling the backend to display them onto the front end. I am having issues also loading the page because there's so many model objects to display, I would like to just wipe them for good. However I keep receiving this error OperationalError at /admin/news/post/ too many SQL variables news being the name of my app Any thoughts? Thanks -
Installing opencv python library in cpanel
I have a django project which using opencv-python Library When i tried to publish it to cpanel shared hosting, i had a problem on the opencv-python library, it couldn't build in the cpanel os So what i tried to do is build it manually in my local pc as 'whl' library, then install it in the cpanel It installed successfully but didn't work because of the 'Gun libc' version My local pc Gun libc version is 2.30, and the cpanel is 2.20 And because i build it in my pc it's built by the 2.3 gunlibc version Anybody know how to solve this problem, or anyway to install opencv-python on the cpanel os?! -
How use django with decouple
I am try to use python-decouple for sensitive data in my project but When i use decouple.config for SECRET_KEY it raises an error error Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/admin/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/admin/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/home/admin/.local/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/home/admin/.local/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/home/admin/.local/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/admin/Legaland/src/sqh/settings/dev.py", line 1, in <module> from ._base import * File "/home/admin/Legaland/src/sqh/settings/_base.py", line 40, in <module> SECRET_KEY = config("SECRET_KEY") File "/home/admin/.local/lib/python3.6/site-packages/decouple.py", line 199, in __call__ return self.config(*args, **kwargs) File "/home/admin/.local/lib/python3.6/site-packages/decouple.py", line 83, in __call__ return self.get(*args, **kwargs) File "/home/admin/.local/lib/python3.6/site-packages/decouple.py", line 65, in get value = self.repository[option] File "/home/admin/.local/lib/python3.6/site-packages/decouple.py", line 113, in __getitem__ return self.parser.get(self.SECTION, key) File "/usr/lib/python3.6/configparser.py", line 800, in get d) File "/usr/lib/python3.6/configparser.py", line 394, … -
Django users can't login after I create an account but admin can and i didnt create any registration form by only manually can add users
I've created a login page as a homepage and only by adding manually in Django administration can create a user. I didn't create a registration form. homepage views.py from django.shortcuts import redirect, render from loginapp.models import Register from django.contrib import messages from django.contrib.auth import authenticate, login , logout def home(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request,username=username, password=password) if user is not None: login(request, user) return render(request, "home.html") else: messages.error(request, "Bad Creds!!") return redirect('/') else: return render(request, "home.html") login page views.py def index(request): return render(request, "index.html") login page name as index.html <form id="stripe-login" method="POST" action="{% url 'home' %}"> {% csrf_token %} <div class="trick" style="padding-bottom: 10px;"> <input type="text" name="username" required> <label for="email">Username</label> </div> <div class=" trick" style="padding-bottom:10px;"> <input type="password" name="password" required> <label for="password">Password</label> </div> <!--div class="field field-checkbox padding-bottom--24 flex-flex align-center"> <label for="checkbox"> <input type="checkbox" name="checkbox">Keep me signed in </label> </div--> <div class="field" style="padding-bottom:10px; padding-top: 10px;"> <input type="submit" name="submit" value="Continue"> </div> <div class="reset-pass" style="padding-top: 20px;"> <a href="#">Forgot your password?</a> </div> <div class="footer-link text-light" style="padding-top:10px;"> <span>Don't have an account? <a href="{% url 'signup' %}">Request for a new account</a></span> </div> </form> -
How do i access the username of user logged in with google in Django from user model
How to access the username of user logged in with google in django all-auth from the user model how can i access the user name of the logged in user with google from user model for example {% for i in user %} {{i.socialaccount_set.all.0.extra_data.name}}//is there a way to acces the user name in this way {% endfor %} My views.py def leaderBoard(request): points= Points.objects.all().order_by("-score") context = {"user": result} return render(request, "Main/lb.html", context) My model.py class Points(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) score = models.BigIntegerField() my htmlfile <div class="leaderboard-table"> {% for i in user %} <div class="board-item"> <div>1</div> <div> {% if i.socialaccount_set.all.0.get_avatar_url %} <img src="{{i.socialaccount_set.all.0.get_avatar_url}}" /> {{i}}//how to access the user name of the googleuser </div> <div>Test's Taken - 30</div> <div>{{i.score}} Points</div> </div> {% endfor %} </div> my custom user model from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin, ) class UserManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError("Users must have an email address") user = self.model(email=self.normalize_email(email), name=name) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, name, password): user = self.create_user( email, name, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, name, password): user = self.create_user( email, name, password=password, ) user.staff = True user.admin … -
Saving updated user password django
I have a user update api that is supposed to update the user's details. I have used set_password() to encrypt the password and from my print statements, it seems to encrypt fine. However when I save the updated user, the password still saves as plain text. What am I missing here ? class UserDetail(APIView): def get_user(self, pk): try: return User.objects.get(pk=pk) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) def put(self, request, pk, format=None): user = self.get_user(pk) data = request.data new_password = data["password"] user.set_password(new_password) user.save() print(user.password) serializers = UserSerializer(user, request.data) if serializers.is_valid(): serializers.save() return Response(serializers.data) else: return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST) -
Django model got an unexpected keyword argument
I want to save crawling data into db, but it has unexpected keyword argument error. some parts of crawling.py for j in range(review_cnt): if soup.select_one(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a > span') != None: if(len(soup.select(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a > span'))) == 2: driver.find_element_by_css_selector(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a').send_keys(Keys.ENTER) current_page = driver.page_source soup = BeautifulSoup(current_page, 'html.parser') time.sleep(1) review_text = soup.select_one(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a > span').text.strip() #텍스트 추출 star_rate = soup.select_one(f'li:nth-child({j+1}) > div._1Z_GL > div._1ZcDn > div._3D_HC > span._2tObC').text review_data.append((place_name, review_text, star_rate)) review_obj = { 'place' : place_name, 'review' : review_text, 'rate' : star_rate } review_dict.append(review_obj) . . . for item in review_dict: reviewData(placeName = item['place'], reviewText = item['review'], starRate = item['rate']).save() #this line has error models.py from django.db import models # Create your models here. class reviewData(models.Model): placeName = models.CharField(max_length=50) reviewText = models.TextField starRate = models.FloatField I don't know where to fix. Should I add something more? -
Data is not appearing on HTML... it is showing empty instead
I have created a Database and also create a form to add data in it. But when I try to show the data on html it shows nothing. My Model is class Bank(models.Model): bankname=models.CharField(max_length=50) acctitle=models.CharField(max_length=50) city=models.CharField(max_length=50) branchname=models.CharField(max_length=50, null=True) branchcode=models.IntegerField(default=0) adddate=models.DateTimeField(default=timezone.now) def __str__(self): return self.bankname My Views def add_bank(request): if request.method=='POST': bankname=request.POST.get('bankname') acctitle=request.POST.get('acctitle') city=request.POST.get('city') branchname=request.POST.get('branchname') branchcode=request.POST.get('branchcode') data=Bank(bankname=bankname,acctitle=acctitle,city=city,branchname=branchname, branchcode=branchcode) data.save(); return render(request, 'add_bank.html') def add_amount(request): banks= Bank.objects.all() return render(request, 'add_amount.html', {'banks':banks}) My Html for displaying data <select name="banks" class="form-control custom-select"> <option value="">Bank:</option> {% for bank in banks %} <option value="{{ forloop.counter }}">{{ banks.bankname }}</option> {% endfor %} </select> Output Image I don't know where I'm making mistake -
"redirect" function of django is not and after submitting the form, user remains on same page
In the function "createProject" of views.py, I want that after submitting the form user should redirect to the "projects" page. But I don't know what is my mistake here. After submitting the form it does not redirect the user to "projects" page but remains on the same page. "views.py" file:- from django.shortcuts import render, redirect from django.http import HttpResponse from .forms import ProjectForm from .models import Project def projects(request): projects = Project.objects.all() context = {'projects':projects} return render(request, 'projects/projects.html', context) def project(request, pk): return render(request, 'projects/single-project.html') def createProject(request): form = ProjectForm() if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): form.save() redirect('projects') context = {'form':form} return render(request, 'projects/project_form.html', context) Here is "urls.py" file:- from django.urls import path from . import views urlpatterns = [ path('', views.projects, name = 'projects'), path('project/<str:pk>/', views.project, name = 'project'), path('create-project/', views.createProject, name = 'create-project'), ] Here is "project-form.html" [I am using Django "ModelForm"]:- from django.db.models.base import Model from django.forms import ModelForm from .models import Project class ProjectForm(ModelForm): class Meta: model = Project fields = ['title', 'description', 'demo_link', 'source_link', 'tags'] Can anyone help me in finding the mistake here ? Why after submitting the form, it is not redirecting it to the "projects" page and remain on … -
Radio buttons are rendering on top of rest of form
I'm using vanilla bootstrap with Python on Django. I've configured a form with radio buttons, however the buttons render on top of the fields as shown in the screenshot below. I've notice that Django puts the radio buttons into a list and I thought that could be the cause, so I tried using CSS to disable the tag but the radio buttons still float on top just without the list bullets. Forms.py class MerchantGroupForm(forms.Form): DO_WHAT_CHOICES=[('merge','Merge'), ('update','Update')] #do_what = forms.ChoiceField(choices=DO_WHAT_CHOICES, widget=forms.RadioSelect(attrs={'class': "custom-radio-list"})) do_what = forms.ChoiceField(choices=DO_WHAT_CHOICES, widget=forms.RadioSelect) merge_merchantgroup = forms.ModelChoiceField(required=False, queryset=MerchantGroup.objects.all().order_by('name'), empty_label="Merge with") name = forms.CharField(required=False) default_ledger = GroupedModelChoiceField(required=False, queryset=Ledger.objects.all().order_by('coa_sub_group__name','name'), choices_groupby = 'coa_sub_group') disable_AI = forms.BooleanField(required=False, label='Disable AI') <form action="/monzo/merchantgroups/update/799/" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="ZWtsz3JDsnUtu1mj6NO3SDlBuyJyEpDgbZUDC6elfTPK2DCwWevD2BpirSZJOhiM"> <div class="form-group"> <label for="id_do_what_0">Do what:</label> <ul id="id_do_what" class="custom-radio-list form-control"> <li><label for="id_do_what_0"><input type="radio" name="do_what" value="merge" class="custom-radio-list form-control" required id="id_do_what_0"> Merge</label> </li> <li><label for="id_do_what_1"><input type="radio" name="do_what" value="update" class="custom-radio-list form-control" required id="id_do_what_1"> Update</label> </li> </ul> </div> <div class="form-group"> <label for="id_merge_merchantgroup">Merge merchantgroup:</label> <select name="merge_merchantgroup" class="form-control" id="id_merge_merchantgroup"> <option value="" selected>Merge with</option> <option value="203">ATM</option> <option value="799">Amazon</option> <option value="200">Post Office</option> <option value="201">Virgin Media</option> <option value="202">www.modelsport.co.uk</option> </select> </div> <div class="form-group"> <label for="id_name">Name:</label> <input type="text" name="name" value="Amazon" class="form-control" id="id_name"> </div> <div class="form-group"> <label for="id_default_ledger">Default ledger:</label> <select name="default_ledger" class="form-control" id="id_default_ledger"> <option value="">---------</option> <optgroup label="Accounts"> <option value="20">Jacks Account</option> … -
Is Mongodb better than Cassandra to be used as a database for my Django and react native project
Being new to Django and learning about it to work on my project along with react native I wanted to know if mongodb is better for working with db than apache Cassandra because I recently did some research on mongo db and found out about djongo but still wanted to know that is there a better database out there to work with in Django and react native . -
django.core.exceptions.FieldError: Unknown field(s) ( message) specified for Message in django error
form.py ( consider all imports ) can anyone point out error that we i am getting message is unknown field class emailForm(forms.ModelForm): class Meta: model = Message fields = ['receiver','subject' ,' message'] labels ={'receiver':'receiver','subject':'subject' , 'message' : ' message'} widgets = {'receiver':forms.TextInput(attrs={"class":'form-control'}),'subject':forms.TextInput(attrs={"class":'form-control'}),'message':forms.Textarea(attrs={"class":'form-control'}),} models.py ( considering all imports ) class Message(models.Model): sender = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='receiver') subject = models.CharField(max_length=1200) message = models.CharField(max_length=1200) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.message views.py ( importing all ) def home(request): form = emailForm(request.POST) if request.method == 'POST' or 'GET': if form.is_valid(): email= request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') user = Message(receiver=email , subject=subject ,message = message ) user.save() form =emailForm() return redirect('inbox') # return redirect('addpost.html') else: form =emailForm() return render(request,"home.html",{'message':form}) -
Datatable save and load table state with Django
Has anyone used Datatable.net library - https://datatables.net/ I want to save the state of the table in the database like column visibility and order. With stateSaveCallback I get all these in a JSON. I wrote an API that saves this data in a SQL table. And on reloading, I want to render the table with the saved state changes. var tableSumm = $('#summary_table').DataTable({ stateSave: true, stateSaveCallback: function (settings, data) { console.log(this.attr("id")) console.log('SAVE', data); var URL = window.location.origin + '/api/state/' + this.attr("id") + '/' fetch(URL, { method: 'POST', dataType: 'json', headers:{ 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', //Necessary to work with request.is_ajax() 'X-CSRFToken': csrftoken }, body:JSON.stringify(data), success: function () {} }) }, stateLoadCallback: function (settings, callback) { console.log('Load', data); var URL = window.location.origin + '/api/state/' + this.attr("id") + '/' fetch(URL, { headers:{ 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', //Necessary to work with request.is_ajax() } }) .then(response => { return response.json() //Convert response to JSON }) },} There are 2 callback methods available to achieve this, stateSaveCallback and stateLoadCallback. I have tried implementing them in my project but was not been able to successfully achieve it. I want the state to be saved in SQL server. I wrote an API that uses saveStateCallback and … -
How to allow user to toggle between color themes in a Django
So I'm working on a Django website and want visitors to the site to click the theme they want. I was able to do it with pure Html/css and Javascipt but now that im moving everything in Django it's not working. I think maybe its my path set up. Fisrt the code in my index.html <h5 style="text-align: center;line-height: 0;">Personalize Theme</h5> {% load static %} <script type="text/javascript" src="../../static/pythonicThinking/script.js"></script> <div id="theme-options-wrapper"> <div data-mode="light" id="light-mode" class="theme-dot" ></div> <div data-mode="blue" id="blue-mode" class="theme-dot"></div> <div data-mode="green" id="green-mode" class="theme-dot"></div> <div data-mode="purple" id="purple-mode" class="theme-dot"></div> </div> <p id="settings-note">*Theme settings will be saved for<br>your next visit</p> </div> the javacript file console.log('Its working') let theme = localStorage.getItem('theme') if(theme == null){ setTheme('light') }else{ setTheme(theme) } let themeDots = document.getElementsByClassName('theme-dot') for (var i=0; themeDots.length > i; i++){ themeDots[i].addEventListener('click', function(){ let mode = this.dataset.mode console.log('Option clicked:', mode) setTheme(mode) }) } function setTheme(mode){ if(mode == 'light'){ document.getElementById('theme-style').href = 'default.css' } if(mode == 'blue'){ document.getElementById('theme-style').href = 'blue.css' } if(mode == 'green'){ document.getElementById('theme-style').href = 'green.css' } if(mode == 'purple'){ document.getElementById('theme-style').href = 'purple.css' } localStorage.setItem('theme', mode) } the setting.py file # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) the urls.py file from django.views.generic import … -
My order is not being saved. forms in django
Here you can see my models.py. class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) imya = models.CharField(max_length=200, null=False) familiya = models.CharField(max_length=200, null=False) tel = models.CharField(max_length=200, null=False) address = models.CharField(max_length=200, null=False) city = models.CharField(max_length=200, null=False) state = models.CharField(max_length=200, null=False) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) Here you can see my forms.py. Here I just created forms, but, the data should be got from template inputs. from django import forms from django.forms import ModelForm from .models import * class OrderForm(forms.ModelForm): class Meta: model = Order fields = '__all__' views.py def checkout(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] form = OrderForm() if request.method == 'POST': name = request.POST.get('name') surname = request.POST.get('surname') email = request.POST.get('email') number = request.POST.get('number') address = request.POST.get('address') city = request.POST.get('city') state = request.POST.get('state') form = OrderForm(request.POST) if form.is_valid(): Order.object.create( imya=name, familiya=surname, tel=number, adres=address, city=city, state=state, ) form.save() return HttpResponse('Заказ отправлен', safe=False) context = {'items':items, 'order':order, 'cartItems':cartItems, 'form':form} return render(request, 'store/checkout.html', context) In my views, I want to create an object for my order model. I tried this code, It's not giving any errors, but it's not working. PLease, help with saving the order. -
learning django and i getting this, TemplateSyntaxError, message
16 {% if request.user.is_authenticated %} 17 <ul class="menu"> 18 <li {% if section=="dashboard" %}class="selected" {% endif %}> 19 <a href="{% url 'dashboard'%}">My dashboard</a> 20 </li> 21 28 {% endif %} this is the code thats giving me the error i don't know what am i doing wrong error message: Could not parse the remainder: '=="dashboard"' from 'section=="dashboard"' -
how to exactly serialize and create of custom user using drf
I am not able to create a user, hitting the endpoint with the following request "http://127.0.0.1:8000/users/" with a following request body { "user": { "first_name": "test100", "last_name": "last100", "email": "user100@gmail.com", "username": "user100", "status": "active", "contact": 1234567890 }, "password": "test_pass_@100" } class User(AbstractUser): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, unique=True, blank=True, null=True) profile_image = models.ImageField(upload_to='image/%Y/%m/%d', blank=True, null=True) status = models.CharField(max_length=255, blank=True, null=True) contact = PhoneNumberField(blank=True, null=True) is_staff = models.BooleanField(default=False, blank=True, null=True) is_active = models.BooleanField(default=True, blank=True, null=True) def find_by_username(self, name): return self.objects.filter(username=name) def find_by_id(self, id): return self.objects.filter(id=id) And this is my views.py class UserViewSet(viewsets.ViewSet): def list(self, request): try: queryset = User.objects.all() serializer = UserResponseSerializer(queryset, many=True) return HttpResponse(json.dumps(serializer.data), content_type="application/json") except: return HttpResponse(status=404) @swagger_auto_schema(request_body=UserRegistrationRequsetSerializer) def create(self, request, *args, **kwargs): try: serializer = UserRegistrationRequsetSerializer(data=request.data) if serializer.is_valid(): serializer.save() return HttpResponse(serializer.data) else: return HttpResponse("Not valid") except: return HttpResponse(status=404) def retrieve(self, request, pk=None): queryset = User.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = UserResponseSerializer(user) return HttpResponse(serializer.data) def update(self, request, pk=None): pass def partial_update(self, request, pk=None): pass def destroy(self, request, pk=None): pass this is my seralizer.py from rest_framework import serializers class UserResponseSerializer(serializers.Serializer): first_name = serializers.CharField(max_length=255, required=True, allow_blank=False) last_name = serializers.CharField(required=True, allow_blank=False, max_length=255) email = serializers.EmailField(max_length=255, required=True, allow_blank=False) username = serializers.CharField(max_length=255, required=True, allow_blank=False) profile_image … -
Why can't the node js server tell i'm connected
I tried running this (https://github.com/dhvanilp/Hybrid-Cryptography) and everything works fine except the nodejs server can't even tell when I open the webpage. The instructions said to run the Nodejs with Django but the 2 cant seem to communicate. please help a noob out. var http = require('http').createServer().listen(4000); var io = require('socket.io')(http); var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // creating an instance of XMLHttpRequest var xhttp = new XMLHttpRequest(); // host of the server var host = 'localhost'; var port = '8000'; console.log('Listening'); // when a connection happens (client enters on the website) io.on('connection', function(socket) { // if the event with the name 'message' comes from the client with the argument 'msgObject', // which is an object with the format: {'user_name': < name >, 'message': < message >}, // it emits for every connected client that a message has been sent, sending the message to the event // 'getMessage' in the client side socket.on('receive', function(msgObject) { // emits the msgObject to the client io.emit('getReceive', msgObject); console.log(msgObject) // url of the view that will process var url = 'http://127.0.0.1:8000//'; // when the request finishes // prepares to send xhttp.open('POST', url, true); // sends the data to the view xhttp.send(JSON.stringify(msgObject)); }); socket.on('send', function(msgObject) { // emits …