Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't add data to the database using a Django form
If I leave everything as it is, then an error pops up when submitting the form "Select a valid choice. That choice is not one of the available choices." And, for example, if in forms.py I change Product.objects.values_list('product_name') to a class with one field, for example, Category.objects.all(), the form is submitted without errors But I need exactly the first option, where I select a specific class field (product_name), so that there are the necessary options in the form in the select... Who knows how to solve this problem? models.py: class Account(models.Model): uploader_mail = models.EmailField(max_length=254) body = models.CharField(max_length=4096) product = models.ForeignKey('Product', on_delete=models.PROTECT) class Product(models.Model): product_name = models.CharField(max_length=400) description = models.CharField(max_length=4096) price = models.DecimalField(max_digits=8, decimal_places=2) geo = models.CharField(max_length=2) product_logo = models.ImageField(upload_to='img/logos', blank=True) category = models.ForeignKey('Category', on_delete=models.PROTECT) def __str__(self): return self.product_name, self.description, self.geo, class Category(models.Model): category = models.CharField(max_length=100) def __str__(self): return self.category forms.py: class AddForm(forms.Form): uploader_mail = forms.EmailField( label='Owner mail', initial='test@test.test', widget=forms.EmailInput(attrs={'class': 'form-control'})) body = forms.CharField( label='Data line by line', widget=forms.Textarea(attrs={'class': 'form-control','wrap': "off", })) category = forms.ModelChoiceField( queryset=Product.objects.values_list('product_name', flat=True), label='Category', empty_label=None, widget=forms.Select(attrs={'class': 'form-select'})) views.py: def edit(request): if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): print(form.cleaned_data) else: form = AddForm() editable = {'form': form, } return render(request, 'goods_list/edit.html', editable) -
ajax not work when click open in new window after right click in django template
i created a link with ajax this is a html coded: <a id="post_click" href="{{ post.online_url}}" rel="nofollow"> <button class="w-100 " type="button" name="button"> <span class="">link</span> </button> </a> and this is ajax : $(function () { $('#post_click').on('click', function () { var Status = $(this).val(); var id = {{post.id}} $.ajax({ url: "/post-click/" + id, data: { }, dataType : 'json' }); }); }); if i push left click ajax work fine in sever side, but when i push left right click and choose open in new window ajax doesnt work -
Django Problem : I want to see reverse order in django admin many to many field
class Question(models.Model): id = models.AutoField question = models.CharField(max_length=100) answer = models.CharField(max_length=100) class TestSeries(models.Model): id = models.AutoField quiz_name = models.CharField(max_length=100) all_question=models.ManyToManyField(MyQuestion) This is my model.py code when i open my admin panel on test series previous added are shown in order : Oldest first i want to see that in newest first manner . please tell me , how can i do that -
Does anyone know how to deploy Redis as cache along Postgres and Digital Ocean App for Django app?
I deployed Django's app with Digital Ocean App service. This is easy and quick without me having to deal with setting up a Ubuntu Droplet or anything like that for Django. I also got Postgres as the main database for the Django app. The problem is when I also set up Redis Managed Database as a cache server for my app, using VPC network connection such as rediss://private-location-on-digital-ocean:port# (also added the Django App and my own IP address as trusted source) - (also installed django-redis using pip) - to my chagrin I either got Internal Server Error or some vague error said that I have to check the log. By the way I did update the requirements.txt to make sure all packages were installed for Redis to run properly with Django app. Also, I set up the Redis as the CACHE backend in settings.py. The only thing I see is that Postgres is being listed as a component for my Django app and Redis DB is not but it's using the same VPC that my Django app is using. What could be the problem that I missed in order for me to get Redis to act as a cache server … -
What is better ways to store id after successful login?
For my project, I am using Angular + Django Rest Framework. I am storing id in local storage (using Angular). But I want to learn other ways to do it. Can we use (In Django) Session Cache How? -
How to detect enters from text and display on html page using html javascript
I have below data from backend(django) "Innovator in Analytical Process & Environmental Instrumentation\r\nT&C:\r\nPayment: 100% advance against PI prior to Dispatch.\r\nPrices: Ex-works Mumbai.\r\nInstl. and Comm. - Inclusive for Mumbai region. For outstation, Travel, Food\r\nand Lodging charges extra.\r\nFreight: In your scope.\r\nGST: Extra @ 18%.\r\nDelivery: 2-3 weeks after receipt of advance payment.\r\nWarranty: 1 Year from the date of installation.\r\nCustomer's scope:\r\n1. All kinds of Civil/Electrical/Plumbing works.\r\n2. Construction or Modification of the Line.\r\n3. Tubing for Sample inlet and outlet with tapping on the line with PU push\r\nconnector.\r\n4. Electrical, LAN and signal cables - Supply and laying.\r\n5. Online or Offline UPS - 1 KVA.\r\n6. SIM/LAN/Wifi/Dongle for connectivity.\r\n7. DM Water and Sulphuric Acid.\r\n8. Mounting of Flow Meter or 3-way valve.\r\n9. Lab Test Reports." Its have enters in the text I wish to show them on frontend in my this code : my text is getting from {{response.remarks}} <ul class="list list-unstyled mb-0 text-left"> <li><h6 class="my-1">Message Displayed </h6></li> <li>{{response.remarks}}</li> </ul> But its showing me like this But want them with enters how can I do this -
Access Postgres generate_series function via Django model syntax
I need to use Django Models to create roughly the following SQL: SELECT series AT TIME ZONE 'utc' AS forecast_hour, app_forecasts.inventory AS inventory FROM generate_series(DATE_TRUNC('hour', TIMESTAMP '2022-05-01 04:00:00+00:00'), DATE_TRUNC('hour', TIMESTAMP '2022-09-03 03:00:00+00:00'), '1 hour'::interval) series LEFT JOIN app_forecasts ON series = DATE_TRUNC('hour', app_forecasts.forecast_at) AT TIME ZONE 'utc' It would look something like: Forecast.objects.annotate(dates=Func(..., ..., Value('1 day'), function='generate_series')) -
How do i get a success message for a model object in django
I'm trying to create an authentication in my project after signing in. I created my models. I want the user to get an error message if he doesn't get the correct pin in the models and successful if he puts in the right pin. I only get the error message but i don't get the success message class Data(models.Model): name = models.CharField(max_length=100) body = models.CharField(max_length=1000000) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) other_name = models.CharField(max_length=200) email = models.EmailField() profile_image = models.ImageField(blank=True) city = models.CharField(max_length= 100) title = models.TextField(null=True, blank=True) middlename = models.TextField(null=True, blank=True) adreess = models.TextField(null=True, blank=True) country = models.TextField(null=True, blank=True) state = models.TextField(blank=True, verbose_name="Biography (Age, Language, Location...)") pin = models.IntegerField() available = models.TextField(null=True, blank=True) checkings = models.TextField(null=True, blank=True) savings = models.TextField(null=True, blank=True) phone_number = models.TextField(null=True, blank=True) first_his = models.TextField(null=True, blank=True) second_history = models.TextField(null=True, blank=True) third_history = models.TextField(null=True, blank=True) last_history = models.TextField(null=True, blank=True) newstate = models.TextField(null=True, blank=True) def __str__(self): return self.first_name This is my view def checkview(request): pin = request.POST['pin'] if Data.objects.filter(name=pin).exists(): messages.success(request, "You have registered successfully") else: messages.error(request, 'Account Suspended, Your Request To Transfer funds Has Been Declined. Contact Support for Help') return redirect('account') This is my Htm file <div class="pagetitle"> <h1>Pin Code Required to Complete Transfer Request</h1> <style> h8{ … -
isort is not sorting as expected
This is my .isort.cfg file: [settings] profile = black group_by_package = true default_section = THIRDPARTY known_first_party = project known_django = django sections = FUTURE,STDLIB,DJANGO,THIRDPARTY,FIRSTPARTY,LOCALFOLDER and this is the import section of my views.py: from random import randint from django.contrib.auth.hashers import check_password, make_password from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Customer from .serializers import GetCustomerSerializer So why isort doesn't allow me to have an empty line between django.contrib.auth.hashers and rest_framework imports? -
djangorestframework does not work when django channel is applied
I am developing a chatting app that allows social login. While developing all restapi functions, including social login functions, and developing chat customers using channel libraries, there was a problem with social login. This code is chatcustomer using websocketcunsumer. import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import * class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name .... this is setting for channel INSTALLED_APPS = [ 'channels', ] ASGI_APPLICATION = 'project.routing.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } routing.py in project root from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) asgi.py import os import django from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') django.setup() application = get_default_application() routing.py in chatapp from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] this is social login views.py @api_view(['POST']) def authenticate_kakao(request): access_token = request.data["access_token"] code =request.data['code'] """ Email Request """ print("process1") profile_request = requests.get( "https://kapi.kakao.com/v2/user/me", headers={"Authorization": f"Bearer {access_token}"}) print("process2") profile_json = profile_request.json() kakao_account = profile_json.get('kakao_account') email = kakao_account.get('email') profile … -
Django NotEqual custom lookup in exclude method
I registered a custom lookup base on this answer and official documentation. # core/custom_lookup.py from django.db.models import Lookup class NotEqual(Lookup): """Missing != operator.""" lookup_name = 'ne' def as_sql(self, *args): lhs, lhs_params = self.process_lhs(*args) rhs, rhs_params = self.process_rhs(*args) return '{} <> {}'.format(lhs, rhs), lhs_params + rhs_params I registered the custom lookup in my app config. # core/apps.py from django.apps import AppConfig from django.db.models import Field from .custom_lookup import NotEqual class CoreConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'core' def ready(self): Field.register_lookup(NotEqual) Then i use it in the exclude method this way. Customer.objects.all().filter(filter).exclude(private=True, user__ne=info.context.user).order_by('-created') The idea here is to get all the customers where user is info.context.user (with private is False or True) OR user is NOT info.context.user but private is False but exclude customers where user is NOT info.context.user AND private is True But whenever I play the query the error below is thrown Related Field got invalid lookup: ne Am I missing something on the registration of the lookup? -
how can i use scrapy with django?
how can I use Scrapy to grab data from other websites with Django as a backend of my website and react for the front end? I've tried before with Bs4 but it wasn't enough, I think scrapy is better with scrapping multiple URLs. -
TypeError: View.__init__() takes 1 positional argument but 3 were given
when a user is registered he should be directly logged in instead of showing the login page views.py thanks in advance from django.contrib.auth import login from django.views.generic import ListView,DetailView,CreateView,UpdateView,DeleteView,FormView class register(FormView): model=task form_class=UserCreationForm template_name='register.html' success_url=reverse_lazy('all') def form_valid(self, form): user=form.save() if user is not None: login(self.request,user) return super(register,self).form_valid(form) urls.py from.views import display_all,display_detail,insert_detail,update_detail,delete_task,login,register urlpatterns = [ path('',display_all.as_view(),name='all'), path('view_detail/<int:pk>',display_detail.as_view(),name='detail'), path('insert_detail/',insert_detail.as_view(),name='insert'), path('update_detail/<int:pk>',update_detail.as_view(),name='update'), path('delete_detail/<int:pk>',delete_task.as_view(),name='delete'), path('login/',login.as_view(),name='login'), path('logout/',LogoutView.as_view(next_page='all'),name='logout'), path('register/',register.as_view(),name='register') register.html <body> <form action="" method="post"> {{form.as_p}} {% csrf_token %} <input type="submit" value="signup"> </form> -
Django - Not Found The requested resource was not found on this server on Production
I was trying to deploy my Django project on Render . Everything works fine except for the media files. I can't figure out the issue here. I have added the followings into my settings.py: DEBUG=False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", ] STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / "staticfiles" STATICFILES_DIRS = [ BASE_DIR / "static" ] MEDIA_URL = '/contents/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/contents/') STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" STATICFILES_STORAGE = "whitenoise.storage.CompressedStaticFilesStorage" urls.py from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) I have created a Post (using models) before deploying. It had an image located a ./static/contents/Screenshot_334.png After deploying this image is accessible at https://someusername.onrender.com/static/contents/Screenshot_334.png . But if I create a new post from the deployed site I get a 404 error. The site doesn't cause any issue while its in the development mode. Here's a portion of LOGS from Render: https://someusername.onrender.com/static/contents/Screenshot_334.png (created while development) is accessible but https://someusername.onrender.com/static/contents/Screenshot_1.png (created post-production) is inaccessible. Also, static files (css, js) working fine. I also tried switching MEDIA_URL and MEDIA_ROOT to 'contents', 'contents/', 'static/contents/' and all the possible variations. -
How to get all data associate with serializers.PrimaryKeyRelatedField
I am trying to get all the data associated with this interest_category serializer. This is what I am currently getting: { "project_title": "Dogs", "project_description": "and cats", "interest_category": [ 4, 7 ], "created_by": 1, "created_at": "2022-09-17T04:31:40.884357Z", "updated_at": "2022-09-17T04:31:40.884357Z" }, What I am trying to get: { "project_title": "Dogs", "project_description": "and cats", "interest_category": [ { "id": 4, "interest_name": "Test" }, { "id": 7, "interest_name": "Business" } ], "created_by": 1, "created_at": "2022-09-17T04:31:40.884357Z", "updated_at": "2022-09-17T04:31:40.884357Z" }, The issue I am having is if I use the below code, I cannot get the interest_category "interest_name" and only have the IDs displayed in a GET request: class InterestSerializer(serializers.ModelSerializer): interest_name = serializers.CharField() class Meta: model = Interests fields = ('id', 'interest_name') class ProjectsSerializer(serializers.ModelSerializer): interest_category = serializers.PrimaryKeyRelatedField( many=True, read_only=True ) class Meta: model = Project fields = [ 'project_title', 'project_description', 'interest_category', 'created_by', 'created_at', 'updated_at', ] def create(self, validated_data): project_category = validated_data.pop("interest_category", None) project_create = Project.objects.create(**validated_data) if project_category: project_create.interest_category.set(project_category) return project_create I have tried using this to GET the data and I can, however when I use this code, I cannot write and set the interest_category, it will just be blank: class InterestSerializer(serializers.ModelSerializer): interest_name = serializers.CharField() class Meta: model = Interests fields = ('id', 'interest_name') class ProjectsSerializer(serializers.ModelSerializer): interest_category = … -
record does not exist or has been deleted.\\n(record: account.move.line(5398,), user: 7) in odoo while updating
I'm getting record does not exist or has been deleted.\n(record: account.move.line(5398,), user: 7) error while updating data to odoo. Following is my code can anyone help to solve this problem. import xmlrpc.client endpoint_url = "/api/account.move/" obj = get_object_or_404(OrderItem, order__id=order_id) invoice_date = obj.order.created_on name = obj.product.varient_name price = obj.total quantity = obj.quantity payment_source = obj.order.payment_method payment_reference = obj.order.order_number common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url)) uid = common.authenticate(db, username, password, {}) models = xmlrpc.client.ServerProxy('{}/xmlrpc/2/object'.format(url)) ids = models.execute_kw(db, uid, password, 'account.move', 'search_read', [[['source_document', '=', payment_reference]]], {'fields': ['partner_id', 'id']}) invoice_id = ids[0]['id'] partner_id_ = ids[0]['partner_id'][0] headers = { "access-token":tokens, "Content-type":"application/jsonp", "Cookie":session_id } api_invoice_line_id = [(1, invoice_id,{'name':name, 'price_unit':price, 'quantity':quantity})] data = { "partner_id":partner_id_, "invoice_date":str(invoice_date), "move_type":"out_invoice", "__api__invoice_line_ids":str(api_invoice_line_id), "payment_source":payment_source, "source_document": payment_reference, "rider":rider_name, "ref":"" } datas_ = json.dumps(data, indent=4) req = requests.put(url+endpoint_url+str(invoice_id), headers=headers, data=datas_) if req.status_code == 200: status = "Update Successful" else: status = str(req.text) return status -
In django function base view how to inherit some opertion that are used in all views functions?
I am using django function base views these operation needed in all views. resourceList=resource.objects.all() params={ 'resourcelist':resourceList } return render(request, html file, params) One solution is that I will type in all my views function. Anyone can help me with a suitable answer for this? -
Django custom save model creating duplicate files
I'm trying to get image uploads to also save as thumbnails, which works. The problem was when I did an update the custom method saved the thumbnail again in a different directory. so I modified my save function to look like this. models.py class Photo(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='photos/%Y%m') thumbnail = models.ImageField(blank=True, upload_to='thumbnails/%Y%m') submitter = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) year = models.ForeignKey(Year, blank=True, on_delete=models.CASCADE) people = TaggableManager(through=TaggedPeople, verbose_name='People') tags = TaggableManager(through=TaggedGeneric, verbose_name='Tags') def save(self, *args, **kwargs): try: this = Photo.objects.get(id=self.id) if this.thumbnail != self.thumbnail: this.thumbnail.delete(save=False) except: if self.thumbnail: img = Image.open(BytesIO(self.thumbnail.read())) if hasattr(img, '_getexif'): exif = img._getexif() if exif: for tag, label in ExifTags.TAGS.items(): if label == 'Orientation': orientation = tag break if orientation in exif: if exif[orientation] == 3: img = img.rotate(180, expand=True) elif exif[orientation] == 6: img = img.rotate(270, expand=True) elif exif[orientation] == 8: img = img.rotate(90, expand=True) img.thumbnail((360,360), Image.ANTIALIAS) output = BytesIO() img.save(output, format='JPEG', quality=95) output.seek(0) self.thumbnail = File(output, self.thumbnail.name) return super().save(*args, **kwargs) def __str__(self): return self.title and my views class PhotoCreateView(LoginRequiredMixin, CreateView): model = Photo fields = ['image', 'title', 'description', 'year', 'people', 'tags'] template_name = 'photoapp/create.html' success_url = '/photo/?page=1' extra_context = {'tags':GenericTag.objects.all().order_by('name'),'people':PeopleTag.objects.all().order_by('name'),} def form_valid(self, form): form.instance.thumbnail = self.request.FILES['image'] form.instance.submitter = … -
[{"non_field_errors":["Invalid data. Expected a dictionary, but got int."]}
Trying to post to my DRF API. But I am getting the following error. I am using Vue.js as my front end. I am able to retrieve the data with no issues. I just cannot write or create a new entry. [{"non_field_errors":["Invalid data. Expected a dictionary, but got int."]} Models: class Interests(models.Model): interest_name = models.CharField(max_length=50) created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "Category name:" + "\n" + self.interest_name + "\n" + "|" + "\n" + "Created By:" + "\n" + self.created_by.username class Project(models.Model): project_title = models.CharField(max_length=255) project_description = models.TextField(max_length=1500) interest_category = models.ManyToManyField(Interests) created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "Project name:" + "\n" + self.project_title + "\n" + "|" + "\n" + "Created By:" + "\n" + self.created_by.username Views: class ProjectView(generics.RetrieveAPIView): queryset = Project.objects.order_by('-created_at') def get(self, request): queryset = self.get_queryset() serializer = ProjectsSerializer(queryset, many=True) return Response(serializer.data) def post(self, request): if request.method == 'POST': serializer = ProjectsSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) class ProjectCategory(generics.RetrieveAPIView): queryset = Interests.objects.all() def get(self, request): queryset = self.get_queryset() serializer = InterestSerializer(queryset, many=True) return Response(serializer.data) Serializer: class InterestSerializer(serializers.ModelSerializer): class Meta: model = Interests fields = ('id', 'interest_name') class ProjectsSerializer(serializers.ModelSerializer): interest_category = … -
Why do you need to use this "f" with dynamic http responses in django?
For example: from django.shortcuts import render from django.http import HttpResponse def view(request, something): return HttpResponse(f' {something} ') I've found many examples like this one, but no explanation of what the 'f' means in 'HttpResponse(f' {something} '), or why is it necessary. It's not used when you don't utilize a captured value from the url. -
am trying to test my project before deploy, i used python manage.py test --debug and am getting this, please i need help to fix it
C:\Users\Videc\Documents\GitHub\blog4>python manage.py test --debug usage: manage.py test [-h] [--noinput] [--failfast] [--testrunner TESTRUNNER] [-t TOP_LEVEL] [-p PATTERN] [--keepdb] [--shuffle [SEED]] [-r] [--debug-mode] [-d] [--parallel [N]] [--tag TAGS] [--exclude-tag EXCLUDE_TAGS] [--pdb] [-b] [--no-faulthandler] [--timing] [-k TEST_NAME_PATTERNS] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [test_label ...] manage.py test: error: ambiguous option: --debug could match --debug-mode, --debug-sql C:\Users\Videc\Documents\GitHub\blog4> -
Having trouble with Django inclusion_tag seeming to have recursive calls
Sorry in advance for the length, I wanted to do my due diligence and also provide as much detail as necessary. I have a navbar template file that is included into a header template file, which is then extended by my rendered templates. In the navbar I want to be able to have a bubble on a menu item that shows how many pending requests there are for a particular model. I've followed this doc over and over and still can't figure out what the issue is. Confusing me even more in my searches are the similar issues others have had but using different versions of Django so I've used the Django doc as the main reference. It seems that the function (the one that is the inclusion tag) is getting called recursively because, while debugging I noticed it runs through once and the request dictionary key is in the context. However, it runs through a second time and at that point there is no request key so it fails. I put it in a try/except block to skip over the error and see what would happen but then it throws a recursive limit reached error. Can someone help with … -
Remove color of element after MouseOver using javascript/Jquery
I'm trying to make a star rating system for my django project using Js and Jquery. I want to change the color of stars when the mouse is on each star. My Html: <div class="user-rating"> <form action="" method="post" class="rate-form"> {% csrf_token %} <button type="submit" class="fa fa-star fa-lg" id="star-first"></button> <button type="submit" class="fa fa-star fa-lg" id="star-second"></button> <button type="submit" class="fa fa-star fa-lg" id="star-third"></button> <button type="submit" class="fa fa-star fa-lg" id="star-fourth"></button> <button type="submit" class="fa fa-star fa-lg" id="star-fifth"></button> </form> <div id="confirm-score"></div> Css: .checked { color: #f2994a;} Javascript code: (function ($) { "use strict"; $(document).ready(function () { const starone = document.getElementById('star-first') const startwo = document.getElementById('star-second') const starthird = document.getElementById('star-third') const starfourth = document.getElementById('star-fourth') const starfifth = document.getElementById('star-fifth') const form = document.querySelector('.rate-form') const confirmBox = document.getElementById('confirm-score') const csrf = document.getElementsByName('csrfmiddlewaretoken') const handleStarSelect = (size) => { const children = form.children for (let i = 0; i < children.length; i++) { if (i <= size) { children[i].classList.add('checked') } else { children[i].classList.remove('checked') } } } // handleStarSelect(2) const handleSelect = (selection) => { switch (selection) { case 'star-first': { // starone.classList.add('checked') // startwo.classList.remove('checked') // starthird.classList.remove('checked') // starfourth.classList.remove('checked') // starfifth.classList.remove('checked') handleStarSelect(1) return } case 'star-second': { handleStarSelect(2) return } case 'star-third': { handleStarSelect(3) return } case 'star-fourth': { handleStarSelect(4) return } … -
Post ID to DRF API but call name
I am really struggling with this one as I am learning. I am trying to call the following: { "id": 2, "interest_name": "Money" }, { "id": 3, "interest_name": "Django" }, { "id": 4, "interest_name": "Test" }, { "id": 5, "interest_name": "Inventory Management" }, { "id": 6, "interest_name": "Design" } With: created () { getAPI.get('api/v1/projects/category') .then(response => { this.ProjectsAPI = response.data console.log('API Data Received') }) .catch(errors => { console.log(errors) }) I am displaying a select field as so: <select id="interest_category" name="interest_category" v-model="interest_category" multiple class="block w-full max-w-lg rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:max-w-xs sm:text-sm"> <option v-for="category in ProjectsAPI">{{ category.interest_name }}</option> </select> I get the following within my rendered Vue page: Money Django Test Inventory Management Design Now, I am trying to select the option but I get this error when I hit submit: [{"non_field_errors":["Invalid data. Expected a dictionary, but got str."]}]} Here is my form code: submitForm(e) { const formData = { project_title: this.project_title, project_description: this.project_description, interest_category: this.interest_category, created_by: this.created_by } axios .post("api/v1/projects/", formData) .then (response => { console.log(response) this.$router.push('/project-dashboard') }) .catch(error => { if (error.response) { for (const property in error.response.data) { this.errors.push(`${property}: ${error.response.data[property]}`) } console.log(JSON.stringify(error.response.data)) } else if (error.message) { console.log(JSON.stringify(error.message)) } else { console.log(JSON.stringify(error)) } }) } } I … -
NGINX ERROR :connect() failed (111: Connection refused) while connecting to upstream
I get that error in title when I cat out the error.log this is how I set my website config inside /etc/nginx/site-availables/ArticleWebsite: server_tokens off; access_log /var/log/nginx/ArticleWebsite.access.log; error_log /var/log/nginx/ArticleWebsite.error.log; # This configuration will be changed to redirect to HTTPS later server { server_name backend.globeofarticles.com; listen 443 ssl; ssl_certificate /etc/letsencrypt/live/backend.globeofarticles.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/backend.globeofarticles.com/privkey.pem; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; } } to explain my situation better, backend.globeofarticles.com is the subdomain, that where the requests are sent from globeofarticles.com or www.globeofarticles.com. Also, Django has 127.0.0.1:8000 host as default. when I access the website (backend subdomain) I get this error: when checking network tab, I get too many redirects actually: with status code 301