Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
For Django, how can I make a button that duplicates a form?
I am making some sort of financial calculator and I have no JavaScript experience. I want to add a button that would allow users to add another asset/amount field in the form. I also want the values to be inputted from the homepage. How would I go about doing this? this is my views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import Assets from .models import PortfolioScan, Item def home(request): if request.method == "POST": if request.POST.get("calculate"): form = Assets(request.POST) if form.is_valid(): t = form.cleaned_data['ticker'] a = form.cleaned_data['amount'] assets = PortfolioScan(ticker=t, amount=a) assets.save() return HttpResponseRedirect('/calculate/') elif request.POST.get("additem"): pass else: form = Assets() return render(request, "portfolioscan/home.html", {"form":form}) forms.py from django import forms class Assets(forms.Form): ticker = forms.CharField(label="ticker", max_length=100) amount = forms.IntegerField(label="amount", max_value=1000000, min_value=-1000000) models.py from django.db import models # Create your models here. class PortfolioScan(models.Model): ticker = models.CharField(max_length=100) amount = models.IntegerField() def __str__(self): return self.ticker def __int__(self): return self.amount class Item(models.Model): portfolio = models.ForeignKey(PortfolioScan, on_delete=models.CASCADE) stock = models.CharField(max_length=100) allocation = models.IntegerField() def __str__(self): return self.stock def __int__(self): return self.allocation home.html <div> <form method="post" action="#"> {% csrf_token %} {{form}} <button type="submit", name="additem", value="additem">Add Another</button> <button type="submit", name="calculate", value="calculate">Calculate</button> </form> </div> I have tried everything in my knowledge and have tried … -
django 3.1 multilanguage site breaks login
I have set up a django 3.1 site that uses 2 languages, English and German, and I use i18n_patterns in my urls.py. The problem is, in my views.py method, I never get a POST request, even though I specify method="POST" in my form. It always comes in as a GET request, and I cannot login. Somewhere along the way, the system changes my POST request into a GET request. urlpatterns = [] urlpatterns += i18n_patterns( path('{}/'.format(settings.DJANGO_ADMIN_URL), admin.site.urls), path('review/', include('review.urls')), path('anmelden_success/', views.anmelden_success, name='anmelden_success'), path('', views.site_login, name='site_login'), path('site_login/', views.site_login, name='site_login'), path('site_logout/', views.site_logout, name='site_logout'), ) I log in with this form, specifying method="POST": <form action="/site_login/" method="POST" id="login-form">{% csrf_token %} <label class="required" for="id_username">Benutzer:</label> <input type="text" name="username" autofocus required id="id_username"> <label class="required" for="id_password">Passwort:</label>&nbsp;<input type="password" name="password" required id="id_password"> <input type="hidden" name="next" value="/review/"> <label>&nbsp;</label><input type="submit" value="Anmelden"> </form> The request comes to my views.py method site_login: def site_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/anmelden_success') else: return HttpResponse("Sorry, you failed to login.") else: if request.user.is_authenticated: return redirect('/review') else: return render(request, 'registration/login.html') Since it somehow gets changed from a POST request to a GET request, my login fails, and I come straight … -
my edit function is not working where are my going wrong?
i am trying to make a edit function for my project but it not working it only updating my five of my variables that are in another table but the rest it isn't updating it - it only update the variables in my custom user model which are first_name,last_name,username and email - it doesnt update the variables in my admin model - where are my going wrong- any help will be appreciated - i am still new in django so excuse any mistakes this is my custom user model class CustomUser(AbstractUser): user_type_data=((1,"Admin"),(2,"senioremployee"),(3,"employee")) user_type=models.CharField(default=1,choices=user_type_data,max_length=20) this is my admin model class admin(models.Model): id = models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser, on_delete=models.CASCADE) Dob = models.DateField() Nationality = models.TextField() Address = models.TextField() Postcode = models.TextField() Telephone = models.TextField() Wage = models.TextField() Passportnumber = models.TextField() passportexpirydate = models.DateField() gender = models.CharField(max_length=255) profile_pic = models.FileField() kinname = models.TextField() kinrelation = models.TextField() kinaddress = models.TextField() kinphonenumber = models.TextField() kinemail = models.TextField() profile_pic = models.FileField() created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects = models.Manager() this is my edit function def edit_admin_save(request): if request.method!="POST": return HttpResponse("<h2> Method Not Allowed </h2>") else: admin_id = request.POST.get("admin_id") first_name=request.POST.get("first_name") last_name=request.POST.get("last_name") username=request.POST.get("username") email=request.POST.get("email") Dob=request.POST.get("Dob") Nationality=request.POST.get("Nationality") Address=request.POST.get("Address") Postcode=request.POST.get("Postcode") Telephone=request.POST.get("Telephone") Wage=request.POST.get("Wage") Passportnumber=request.POST.get("Passportnumber") passportexpirydate=request.POST.get("passportexpirydate") gender=request.POST.get("gender") kinname=request.POST.get("kinname") kinrelation=request.POST.get("kinrelation") kinaddress=request.POST.get("kinaddress") kinphonenumber=request.POST.get("kinphonenumber") kinemail=request.POST.get("kinemail") if request.FILES.get('profile_pic',False): profile_pic=request.FILES['profile_pic'] fs =FileSystemStorage() … -
How to configure a django model in such a way, that one model will only migrate to one specific database?
say I define a parameter "db_select" inside a "params" class in my model, and I want all migrations from this model to automatically route to that mentioned database. Similarly for other models with other db_select option to be automatically route to their respective database. How should I write my routers.py script ? I am using django 3.1.4 My Models.py: from django.db import models # Create your models here. class Project(models.Model): startDate=models.DateField() endDate=models.DateField(max_length=20) name=models.CharField(max_length=20) assignedTo=models.CharField(max_length=30) priority=models.IntegerField() class params: db_select = 'default' my Database settings: DATABASE_ROUTERS=('movieForm.dbrouters.myRouter',) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'projectInfo', 'USER': 'root', 'PASSWORD': '123@abc', }, 'movie': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'movieDB', 'USER': 'root', 'PASSWORD': '123@abc', } } -
Django-Compressor won't work in offline mode with custom S3 domain
I get the following error whenever a custom domain for the S3 endpoint is used. # WORKS AWS_S3_CUSTOM_DOMAIN = 'example.fra1.digitaloceanspaces.com/{}'.format(AWS_STORAGE_BUCKET_NAME) # DOES NOT WORK ⁉️ AWS_S3_CUSTOM_DOMAIN = 'cdn.example.com/{}'.format(AWS_STORAGE_BUCKET_NAME) CommandError: An error occurred during rendering /home/<user>/<app>/templates/public/index.html: 'https://cdn.example.com/storage/static/node_modules/nouislider/distribute/nouislider.min.css' isn't accessible via COMPRESS_URL ('https://example.fra1.digitaloceanspaces.com/storage/static/') and can't be compressed If I go to either url the file is accessible, hence its likely that the CDN is ok, URLs are correctly defined, CORS are fine too. Also without django-compressor subdomain delivery had been working fine, leading me to believe the issue is not with django-storages I've been trying for several hours and ultimately had to do a temporary fix by setting the AWS_S3_CUSTOM_DOMAIN to be the same as the AWS_S3_ENDPOINT_URL. However this is not ideal. Please see the implementation below. /requirements.txt Django==3.1.4 ... boto3~=1.16.46 botocore~=1.19.46 s3transfer~=0.3.3 ... django-storages~=1.11.1 django-compressor~=2.4 /config/settings.py ... # ========================================================== # DJANGO-STORAGES # ========================================================== if LOCALHOST_MODE: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static/'), ] else: AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = 'storage' AWS_S3_ENDPOINT_URL = 'https://example.fra1.digitaloceanspaces.com' # WORKS ⚠️ AWS_S3_CUSTOM_DOMAIN = 'example.fra1.digitaloceanspaces.com/{}'.format(AWS_STORAGE_BUCKET_NAME) # DOES NOT WORK ⁉️ AWS_S3_CUSTOM_DOMAIN = 'cdn.example.com/{}'.format(AWS_STORAGE_BUCKET_NAME) AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' AWS_DEFAULT_ACL = 'public-read' STATICFILES_DIRS = … -
Using Javascript in executing a Search by title for items in a Django Project
I am adding a Search functionality to my E-commerce Project using Javascript, I have followed a tutorial that explains that when writing the title in the search bar only the items with the same letter appears. In my project, it was working fine for basic HTML but I am trying to make it a little more complex to include a complete card with some details such as price, not just the title. Here is the model.py class Item(models.Model): title = models.CharField(max_length=100) image = models.ImageField(blank=False, upload_to=upload_design_to) price = models.DecimalField(decimal_places=2, max_digits=100) discount_price = models.DecimalField(decimal_places=2, max_digits=100, blank=True, null=True) timestamp = models.DateTimeField(default=timezone.now) Here is the views.py class ItemListView(ListView): model = Item paginate_by = 12 template_name = "store/product_list.html" ordering = ['-timestamp'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs_json"] = json.dumps(list(Item.objects.values()),cls=DjangoJSONEncoder) return context Here is the scripts.py <script> const data = '{{qs_json}}' const rdata = JSON.parse(data.replace(/&quot;/g, '"')) console.log(rdata) const input = document.getElementById('search_here') console.log(input) let filteredArr = [] input.addEventListener('keyup', (e)=>{ box.innerHTML = "" filteredArr = rdata.filter(store=> store['title'].includes(e.target.value)) console.log(filteredArr) if (filteredArr.length > 0){ filteredArr.map(store=>{ box.innerHTML += `<b>${store['title']}</b><br>` }) } else { box.innerHTML = "<b>No results found...</b>" } }) </script> Here is the template.html <input id="search_here" class="mb-2 form-control" placeholder="Type to search..."> <!--Card--> <div id="box" class='row card-group'> {% for item … -
Django + Html: Is it possible to display the initial value in a <select> before change is made so they can see initial
Django + Html: Is it possible to display the initial value in a before change is made, so that if user dont want to update they can leave it as it is. So current i have not choice but to do this in my account update page. Is there a way to make it such that i can query the initial date of birth so i dont have to reselect my date of birth everytime i update other fields in the same form. Thanks views.py def edit_account_view(request, *args, **kwargs): user_id = kwargs.get("user_id") account = Account.objects.get(pk=user_id) if account.pk != request.user.pk: return HttpResponse("You cannot edit someone elses profile.") context = {} if request.POST: form = AccountUpdateForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() return redirect("account:view", user_id=account.pk) else: form = AccountUpdateForm(request.POST, instance=request.user, initial={ "id": account.pk, "date_of_birth": account.date_of_birth, } ) context['form'] = form else: form = AccountUpdateForm( initial={ "id": account.pk, "date_of_birth": account.date_of_birth, } ) context['form'] = form context['DATA_UPLOAD_MAX_MEMORY_SIZE'] = settings.DATA_UPLOAD_MAX_MEMORY_SIZE return render(request, "account/edit_account.html", context) forms.py class AccountUpdateForm(forms.ModelForm): class Meta: model = Account fields = ('username', 'date_of_birth') html <h6 class="mt-4 field-heading">Date of Birth</h6> <input type="date" name="date_of_birth" id="input_dateofbirth" class="form-control" placeholder="Date of birth" required required value="{{form.initial.date_of_birth}}"> <p >{{form.initial.username}}'s Birthday: {{form.initial.date_of_birth}}</p> <p style="color: red;">Reselect your Birthday date again during update … -
Difficulty accessing and working with Django models/QuerySets
My goal is to pull ship data once I pick the ship number but I have no idea how. Here is my model setup from django.db import models from django.contrib.auth.models import User class Hull (models.Model): hull = models.CharField(max_length = 33, ) def __str__(self): return self.hull class Hull_Spec(models.Model): ship = models.ForeignKey(Hull, on_delete=models.CASCADE) speed = models.FloatField() depth = models.FloatField() remarks = models.CharField(max_length =300) def __many_fields_simple_array__(self): return [self.remarks, self.depth, self.speed] Here is what I try starting data hull = SS1 depth = 10 speed = 10 remarks = 'remarks' from main.models import Hull. Hull_Spec hull = Hull.objects.get(hull = 'SS2') specs = hull.hull_spec_set.all() #which returns <QuerySet [<Hull_Spec: Hull_Spec object (2)>]> This is where I get stuck. I can get all of the information if I use the id but I have no idea how to retrieve a spec list's id unless I retrieve it from the terminal as shown above. Is there another way I can retrieve the data from the queryset without having to use get(id =) since I know already which ship this spec data corresponds to already? -
Why is Django authentication is now working for AbstractUser
So I have these Django models in the users app, and I have added AUTH_USER_MODEL = 'users.User' to settings.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): login_count = models.PositiveIntegerField(default=0) class Supplier(User): company_name= models.CharField(max_length=30) company_domain=models.CharField(max_length=30) class Meta: verbose_name = 'supplier' verbose_name_plural = 'suppliers' class Worker(User): ACCOUNT_TYPE = ( ('1', 'Admin'), ('2', 'Regular'), ) is_hub_manager = models.BooleanField(default=False) account_type = models.CharField(max_length=1, choices=ACCOUNT_TYPE) class Meta: verbose_name = 'worker' verbose_name_plural = 'workers' I also created an authenetication endpoint using Django rest framework. Surprisingly when I authenticate the admin everything works well. When I create a supplier and try to authenticate them. They always return invalid credentials. Here are my API views from rest_framework.generics import GenericAPIView from .serializers import UserSerializer from rest_framework.response import Response from rest_framework import status from django.conf import settings from django.contrib import auth import jwt class LoginView(GenericAPIView): serializer_class = UserSerializer def post(self, request): data = request.data username = data.get('username', '') password = data.get('password', '') user = auth.authenticate(username=username, password=password) if user: auth_token = jwt.encode({'username': user.username}, settings.JWT_SECRET_KEY) serializer = UserSerializer(user) data = {'user': serializer.data, 'token': auth_token} return Response(data, status=status.HTTP_200_OK) # SEND RES return Response({'detail': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) What could I be doing wrong? -
Bootstrap modal to confirm deletion
When I loop over my images I have an icon that you can click to delete the image. Instead I'd like to have a modal pop up to confirm the deletion. The only problem is I don't want to repeate the code for the modal for each image. I need a way to pass the image id to the modal. I was thinking I could pass the id in through an onClick but I'm not sure that will work with the Bootstrap modal. Here's how I'm currently deleting: {% for image in images %} <img src="{{image.image.url}}"> <form method="POST" action="{% url 'products:delete_image> {% csrf_token %} <button type="submit" rel="tooltip" title="Remove"> <i class="material-icons">close</i> </button> </form> {% endfor %} Here's the modal code I'd like to integrate <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> -
Django: Template rendering error: NoReverseMatch. How to match necessary pattern using regex?
I am using django_filters and have a set of drop downs that, upon selection, filter and show consequent list from all possible objects. In other words, a simple online directory-like function. I want to pass the querysets to a new view so that the filtered list has its own separate web page. When trying to pass the data to the new view, upon button click, I receive a NoReverseMatch template rendering error. If I don't try to pass it to a new view, but just keep the results on the same page, the url of that page changes from: animal\search\ to animal\search\?type=5&ageGroup=2 and shows all necessary data as expected. I want this data to pass from animal\search, where the user selects desired filter options with the two drop downs, to animal\results\?type=5&ageGroup=2. How can I match this url pattern in regex or otherwise? Or is the problem in my view? Reverse for 'visitor_results_view' with arguments '(<django.forms.boundfield.BoundField object at 0x104847e80>, <django.forms.boundfield.BoundField object at 0x103460c88>)' not found. 1 pattern(s) tried: ['animals/results/(?P<type>[0-9]+)\\&(?P<ageGroup>[0-9]+)/$'] urls.py path('results/<int:type>&<int:ageGroup>/', views.AnimalSearchListView.as_view(), name='visitor_results_view'), path('search/', views.AnimalFilterView.as_view(), name='animalFilter_view'), animal/search.html <form class="form-inline justify-content-center" method="GET" action="{% 'url animals:visitor_results_view' type=filter.form.type ageGroup=filter.form.ageGroup %}"> <div class="col-md-3"> {{ filter.form.type | bootstrap}} </div> <div class="col-md-4 "> {{ filter.form.ageGroup | bootstrap}} … -
How to convert UTC to EST in Django
I am trying to convert UTC to EST in a view and display this in a template. Currently the code seems to have not effect. Here is the view: from django.shortcuts import render, redirect, get_object_or_404 from .models import Article from .models import Article Image from .models import Article Specs from datetime import datetime from django.utils import timezone from django.core.paginator import Paginator def detail(request, article_id): article = get_object_or_404(Article, pk=article_id) image_all = ArticleImage.objects.all() specs_all = ArticleSpecs.objects.all() # est = pytz.timezone('Pacific/Auckland') article_release_datetime = article.releaseDate.astimezone(est) # datetime_now = datetime.now(timezone.utc) datetime_now.astimezone(est) release_countdown = article_release_datetime - datetime_now # (days, remainder) = divmod(release_countdown.seconds, 86400) (hours, remainder) = divmod(remainder, 3600) (minutes, seconds) = divmod(remainder, 60) # return render(request, 'shoes/detail.html', {'article': article, 'image_all': image_all, 'specs_all': specs_all, 'days': days, 'hours': hours, 'datetime_now': datetime_now, 'minutes': minutes, 'seconds': seconds, 'release_countdown': release_countdown}) Here is the template:: enter code here -
django passing multiple parameters to JS document.location.url
In a Django template I am trying to redirect to a different view on a button click through JS. The url needs multiple arguments. I am able to pass multiple argument but when I check the kwargs in the view the values are wrong. The first argument grabs most of the second argument as well. Here is how it looks (Pdb) kwargs {'id1': 1659165, 'id2': 6} Here id1 should be 1659 and id2 should be 1656. Here is the JS code: compare_btn.onclick = function() { var m1=cube1_id.innerHTML; var m2=cube2_id.innerHTML; document.location.href = '{% url "cubes:cube-comparison" id1=11 id2=22 %}'.replace(11,m1).replace(22, m2); } Here is the url: path('cube-comparison/<int:id1><int:id2>', CompareCube.as_view(), name='cube-comparison') I have read one two 3 4 5 and some other questions. Its only one place where I have to use JS so I want to avoid using some library. Thanks for any help. -
HTTPError "message": "MISSING_EMAIL", CODE=400, IN Django Firebase Database
When we login that error occured enter image description here -
Why is Django Celery Beat not starting?
I have been working on this issue for about 4 days now, and it's been extremely frustrating. I would greatly appreciate it if somebody would answer this question for me. I am working on a Django Project that requires me to periodically check objects and some files in the media directory and delete them if outdated. After referring to the celery documentation , I set up everything properly (at least I think), and went ahead to run the program. I first ran my project on one terminal window, then ran a redis server using redis-server on another terminal window. Using a third terminal window, I ran the following: (djangoenv) Daeyongs-Air:Data_Science_Project daeyong$ celery -A Data_Science_Project worker -l info -------------- celery@Daeyongs-Air.fios-router.home v5.0.5 (singularity) --- ***** ----- -- ******* ---- macOS-10.16-x86_64-i386-64bit 2021-01-02 02:57:54 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: Data_Science_Project:0x7f9b0e59f1f0 - ** ---------- .> transport: redis://localhost:6379// - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . Data_Science_Project.celery.test . task_number_one [2021-01-02 02:57:55,154: INFO/MainProcess] Connected to … -
ValueError: Cannot query "": Must be "" instance
I have a quiz app where users can attempt each quiz as many times as they wish. I am now trying to show some quiz stats on the user's profile. What I'm struggling with is showing the user's average score across quizzes. So first, I get the total number of correct answers: correct_answers = QuizTaker.objects.filter(user = self.user, completed = True).aggregate(Sum('correct_answers'))['correct_answers__sum'] This works as expected. Now I need to get the number of attempts per quiz and multiply this by the number of questions in each quiz. Then I would be able to calculate the average score. I got stuck trying to get the number of attempts per quiz. If I hard code it as follows, it works: number_attempts = QuizTaker.objects.filter(user = self.user, completed = True, quiz__title='Afrika').aggregate(Max('attempt_number'))['attempt_number__max'] But I need the max number of attempts for every quiz. So I need to do a for loop. quiztakers = QuizTaker.objects.filter(user = self.user, completed = True) max_attempts = [] for quiz in quiztakers: number_attempts = QuizTaker.objects.filter(user = self.user, completed = True, quiz=quiz).aggregate(Max('attempt_number'))['attempt_number__max'] attempts.append(number_attempts) return max_attempts But then this gives me the following error: ValueError at /accounts/profile/ Cannot query "Username- Quiz: Afrika - Attempt number: 2": Must be "Quiz" instance. The relevant models: class … -
Django: How To Sort ManyToManyField By Alphabetical Order
I have a model that stores the genres/categories of items which can then be selected in form by multiple choice checkboxes. I have want to be able to add genres to the database and then have them slot in to their part in the alphabetical order. I could just enter the values in alphabetical order but that makes it harder to add more later so im trying to find if there is a better way to do it. i have saw someone using class meta: order, but i don't know if that can be used to sort a-z here is some relevant info models.py class Genres(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = "Genres" class Post(models.Model): genres = models.ManyToManyField(Genres, null=True, blank=True) forms.py genre_choices = Genres.objects.all().values_list('name', 'name') genre_choices_list = [] for item in genre_choices: genre_choices_list.append(item) class NewPost(forms.ModelForm): genres = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class': 'form_input_select_multi'}), choices=genre_choices_list) -
Django and yFinance Python integration
I am very new to this. Trying to grab data from yFinance and view it in a web browser using the Views available in Django. The HomePageView renders in the browser as expected but the CompanyDetails does not. Also, there are no known errors... from django.views.generic import TemplateView from django.views import generic import yfinance as yf class HomePageView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['my_thing'] = 'hello world, this is dynamic - 500%' return context class CompanyDetails(generic.DetailView): template_name = 'home.html' def get_context_data(self, **kwargs): tickerdata = yf.Ticker("MSFT") tickerinfo = tickerdata.info investment = tickerinfo['shortName'] context = super().get_context_data(**kwargs) context['ticker'] = investment return context -
I keep getting a Bad Request error due to a GET in my drf login view
Not sure what the problem is, I originally had a genericAPIview used as my user login view that had these errors: Method Not Allowed: /auth/login and "detail": "Method \"GET\" not allowed." So I added a GET method like so: class LoginAPIView(generics.GenericAPIView): permission_classes = [AllowAny] serializer_class = LoginSerializer # I ADDED THIS GET METHOD TO SOLVE FOR ABOVE def get(self, request, format=None): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data) def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) Adding the GET function did solve for "Method \"GET\" not allowed.", but now I'm getting this new error: Bad Request: /auth/login/ Here are my app urls.py urlpatterns = [ path('register/', CustomUserCreate.as_view(), name="register"), path('login/', LoginAPIView.as_view(), name="login"), path('home-auth/', include('rest_framework.urls', ] Here are my project urls.py urlpatterns = [ path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), # path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('admin/', admin.site.urls), path('home/', include('bucket_api.urls', namespace='bucket_api')), path('auth/', include('users.urls')), path('home-auth/', include('rest_framework.urls', namespace='rest_framework')), ] Any tips on how I can solve for the errors above? -
Django: Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['$']
I'm a new face to Django so please be considerate to if ever my problem is something stupid. In this case I want to delete an item in my database, if I click on the button, the html will pass an id to views.py, then the funtion Delete() will delete this item. But whatever I tried it dosen't have any response. Now I add action="{% url 'todolist:delete' todo.id %}" in home.html, but it met some error : NoReverseMatch: Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['$'] , and I don't know how to solve it. So please give me some advice, I'll be really grateful. My codes are as follows: project/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('todolist.urls', namespace='todolist')), ] todolist/urls.py: app_name = "todolist" urlpatterns = [ path('', views.Add, name = 'add'), path('', views.Delete, name = 'delete'), ] home.html: <form action="{% url 'todolist:delete' todo.id %}" method="post"> {% csrf_token %} <table> <tbody> {% for each in todo_list %} <tr> <td><div class="thing"><input type="checkbox" name="done" value="done"><label>{{each.todo}}</label></div></td> <td><input type="button" class="edit" name="edit" value="E"></td> <td><input type="button" class="delete" name="delete" value="x"></td> </tr> {% endfor %} </tbody> </table> </form> views.py: def Delete(request, id): if 'delete' in request.POST: todo = Todo.objects.get(id=id) todo.delete() todo_list = Todo.objects.all() return … -
Django multiple user with using AbstracBaseUser and login email field
I want to use different users in my own project. Users will have different features and I want to log in by e-mail. I'm creating it using AbstracBaseUser, and there should be different login and register pages for both users. Can you tell me the sample code or project about it. -
Python Django - HTML Radio button truncates all letter after space when assigning value
By my read of the code shown below, clicking Test 1 or Test 2 should return Test 1 or Test 2, whichever was clicked; however, instead Test is only returned. Essentially everything following the space is truncated in the value field. Why is this happening? Thanks for your input! HTML <div> <form action = '/test_out/' method = 'POST'> {% csrf_token %} {% for item in test_var %} <input type = "radio" value = {{ item }} name = 'clicked'> {{item}} <br><br> {% endfor %} <input type = 'submit' text = 'Modify Hull'> </form> </div> views.py def test(response): return render(response, 'main/hull_view.html', {'test_var': ['Test 1','Test 2']}) def test_out(response): return HttpResponse(response.POST.get('clicked')) -
Sending items to json using dump not working properly
I am not an expert in javascript but I am trying to learn bit by bit. I am trying to add a search function for my project, so I am starting by sending the item list to JSON using the following: views.py class ItemListView(ListView): model = Item paginate_by = 12 template_name = "store/product_list.html" ordering = ['-timestamp'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs_json"] = json.dumps(list(Item.objects.values())) return context but I keep receiving an error Object of type Decimal is not JSON serializable My question: Why am I receiving this error although I am following a tutorial and this error didn't show up and how do I fix it? -
Django order by ID on Union
I'm trying to order this queryset union by specified ID using Case and When, but I keep getting this error on both SQLite and Postgres with Django 3.1, Py 3.8 (and PG 12.3, not sure about SQLite): django.db.utils.DatabaseError: ORDER BY term does not match any column in the result set. This is the test case: _values = ["id", "parent_id", "parent__title", "created"] class TestBlah(TestCase): def test_order_by(self): a = A.objects.create() b = C.objects.create(parent=B.objects.create()) asd = ( A.objects.annotate( parent_id=models.Value(-1, output_field=models.BigIntegerField()), parent__title=models.Value("", output_field=models.CharField()) ).values(*_values).union(C.objects.values(*_values)) .order_by(models.Case(*[models.When(pk=obj.id, then=i) for i, obj in enumerate([b, a])])) ) My models: from django.db import models class Base(models.Model): id = models.BigAutoField(primary_key=True) created = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class A(Base): ... class B(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=255) class C(Base): parent = models.ForeignKey(B, on_delete=models.CASCADE) It seems like the queryset is not yet evaluated and it's simply Django verifying everything. Anyone know what's up? -
Escape colon in a DismaxString in Scorched/Sunburnt/Solr
I'm using scorched for interfacing my Django code with my Solr instance: response = si.query(DismaxString(querydict.get('q')).execute() I'm using DismaxString because I want to be able to do exact searches (strings within "") and DismaxString doesn't escape characters. Nevertheless, in my data I have colons (e.g. Col: Mackay's Reel) and I don't want Solr to interpret that colon as a 'field' query: "metadata":[ "error-class","org.apache.solr.common.SolrException", "root-error-class","org.apache.solr.common.SolrException"], "msg":"undefined field Col" How can I esccape all the colons and still retaining the unescaping of "?