Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 "? -
Use checkboxes with custom Django form
I'm trying to get Checkboxes to work with my custom form but experiencing some issues. A similar approach using Select inputs works fine, thought it would be similar. By doing {{ form.answer }} I get it to render in my template, but nothing is being saved once I press submit. The column is an integer field since I want to store values between 1-5, and not just true or false answer = models.IntegerField(default=None, null=False) Worth mentioning is that this particular column will store only one value, so the MultipleChoiceField() might be misleading. Will need to change that to the correct one whichever that is later on. My form class EditProfile(UserChangeForm): USER_OPTIONS = ( ('1', 'apple'), ('2', 'banana'), ('3', 'orange'), ('4', 'pear'), ) answer = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=USER_OPTIONS) class Meta: model = Person fields = ( 'answer', ) exclude = ( 'password', ) Any clues or feedback would be appreciated! -
Creating drop down menu in html and css (strange error)
Before you read: please do not judge me on every little thing. I am a beginner to this sort of thing and I am just trying to get some practice. Only comment my mistakes if they are either relevant to the conversation or truly helpful. I've looked over and over at my code and stackoverflow answers but nothing has what I need. I want to create a dropdown menu (you hover on a button and multiple links appear in a vertical line below it). I have been having trouble because the links are horizontal instead of vertical when I hover. I have no idea why. I thought this may be because the display style on my nav bar is set to inline, but I used id's in my css, so that should override the navbar classes. I'm very confused. Someone please help. Here is the relevant code (yes, I am using django): <style> #dropdown {display: none;position: relative;background-color: #dde000; padding: 0px;z-index: 1; left: 970px; top:45px;} #drop:hover #dropdown {display:block;} div.navbar {border: 2px outset gray; position: relative; margin-left:-21px; height:45px; background: #dddddd; margin-top:-6px; left: 15px;} .navbar a {height: 23px; display:inline; text-decoration: none; color: black; padding: 10px; float: left; background: #dddddd; padding-top:12px;} .navbar a:hover {background: … -
Django Storages [file upload to was s3]
I am using django storages library for upload my files to s3. I want to understand how this file uploads works , does the file uploads to s3 folder directly or it uploads to my server and then goes to s3? How does the file upload works in django storages. If I upload multiple files , will they use bandwidth of my server of will they be directly uploaded to s3 and will not slow the speed of my server. Thank you -
Populating django model with objects from other model
I'm new to django, but working on an app for a volunteer sailing organization in my local area. Not sure how to ask this question since it's fairly general but I want the following to happen based on two models; Yacht class (boat name, skipper, color, etc.) Race_Event class (event date, time results for each boat) Step 1: The user will need to create a Race_Event each week. I want the boats from the Yacht model to be loaded into the Race_Event. Step 2: The user will enter race times for each boat. Is there a way to pre-load objects from one model into another? With a ForeignKey the user has to add the boats each time. Any direction for me to research would be helpful. Thanks -
how do I save properly manytomany field in django?
I am trying to save an m2m field where my JSON takes an array where of tactics where it should store n times tactics appear in the list, but how can I do this properly? in my following case, it should be stored two times since the technique is shared in two tactics, but how do I achieve the following? for technique in src_techniques: for data_technique in technique: techniques = { technique_id = data_technique['technique_id'] technique_name = data_technique['technique_name'] tactics = data_technique['tactics'] } Technique.objects.get_or_create(**techniques) src_techniques [{"id":1,"source_name":"mitre-attack","tactic_id":"TA0009","tactic_url":"https://attack.mitre.org/tactics/TA0009","tactic_name":"Collection"}] src_techniques [{'technique_id': 'T1548', 'technique': 'Abuse Elevation Control Mechanism', 'url': 'https://attack.mitre.org/techniques/T1548', 'tactic': ['Collection', 'Defense Evasion']}] models class Technique(models.Model): technique_id = models.CharField(max_length=10) technique_name = models.CharField(max_length=40) tactics = models.ManyToManyField(Tactic, blank=True, null=True) class Tactic(models.Model): tactic_name = models.CharField(max_length=100) -
Trying to load data into databse through web browser: save() prohibited to prevent data loss due to unsaved related object 'ship'
I'm at a total loss as to why I get this error. When I run similar code in the python shell I never get this error but when I try to do this through the web browser I get this error. Any idea why this happens? FYI, I'm a total beginner. 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 __str__(self): return self.remarks views def new_ship (response): x = Hull x.objects.create(hull = response.POST.get('ship')) Z = Hull(hull = response.POST.get('ship')) Z.hull_spec_set.create(speed = response.POST.get('speed'), depth = response.POST.get('depth'), remarks = response.POST.get('remarks')).save() return HttpResponse('Success') html user interface <div> <form action = '/new_ship/' method = 'POST'> {% csrf_token %} <table> <col> <tr> <td><input type = 'text' name = 'ship'>Hull</input></td> <td><input type = 'text' name = 'speed'>Speed</input></td> </tr> <tr> <td><input type = 'text' name = 'depth'>Depth</input></td> <td><input type = 'text' name = 'remarks'>Remarks</input></td> </tr> <tr> <td><input type="submit" value="Submit Fields" id = 'button_1'></td> </tr> </col> </table> </form> </div> -
Django - User can upload an image, but the image does not display - HTML issue? (Beginner help)
I'm new to Django and creating a way for users to upload an image onto a post. Then the image should be visible on each individual post's page. So far in my 'create' function users can successfully create a post and upload a photo. The photo is uploaded into my project but it is still not displaying at all. Any help is greatly appreciated. I think the issue is how the class in views.py, and the html in index.html is written. Just not sure how to fix. views.py to create the post: def create(request): if request.method == 'GET': context = { 'form': CreateForm(), 'form1': CategoryForm(), 'img_form': ImgForm(), } return render(request, "auctions/create.html", context) else: form = CreateForm(request.POST, request.FILES) form1 = CategoryForm(request.POST, request.FILES) img_form = ImgForm(request.POST, request.FILES) if form.is_valid(): title = form.cleaned_data['title'] description = form.cleaned_data['description'] starting_bid = form.cleaned_data['starting_bid'] if form1.is_valid(): category = form1.cleaned_data['category'] if img_form.is_valid(): image = img_form.cleaned_data['image'] auctionCreated = Listings.objects.create( title=title, description=description, starting_bid=starting_bid, ) categoryCreated = Categories.objects.create( category=category, ) ImageCreated = Img.objects.create( image=image, ) return redirect('index') views.py - this should show a list of each post (on the homepage) and each image should be visible but the image is not appearing: def index(request): items = Listings.objects.all() images = Img.objects.all() return render(request, … -
How to improve the structure of my django project?
Oops good night, recently I started studying django and I came across the problem of structuring the project. Using the codes as an example (suppose you have 1 billion business rules there), I rewrote the user model (user, works perfectly), created a custom manager custom queryset, views (which already comes in startapp) and created a service (another name for "put the business rule"). And my doubts are: 1 ° - Is this basic structure correct? 2 ° - What could I change to further improve the structure of the project? 3 - What is the best way to call my services? static method, instance or class method? 4 - Is it better to put the services of each application in class or to separate everything into functions? 5 ° - If I have a function call from a service view and this function calls another internal function, is it better to instantiate a class to be able to call the functions with the self or to position the function above the other to be able to call? models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db.models import Q from .manager import UserManager class User(AbstractBaseUser): REQUIRED_FIELDS = ['name', … -
Can I use a custom Django manager on a given set of objects?
I have some queryset logic that I would be happy to have in a Manager. I already have the objects in an existing queryset, and I would just like to reorder them. I am thinking of doing something like this: class WorkdayManager(Manager): def ordered_by_time_available(self, object_set): results = object_set.annotate( remaining=F('duration') - F(Coalesce((Sum('record__minutes_planned'), 0)))) return results.order_by(['-remaining']) And I would like to use it like this: object_set.ordered_by_time_available() Would this work? Or should I be using something different? -
django JSONField doesn't accept value
I add a JSONField for one of my models. I want to create an instance of that model in admin panel but that JSONField returns a validation error (Enter a valid JSON.) how I can fix this?? model: class Product(models.Model): category = models.ManyToManyField(Category, related_name='products') name = models.CharField(max_length=500) slug = models.SlugField(max_length=500, allow_unicode=True, unique=True) image_1 = models.ImageField(upload_to='products_pic/%Y/%m/%d/', null=True, blank=True) description = models.TextField(null=True, blank=True) attribute = models.JSONField(default={}) price = models.PositiveIntegerField() discount = models.PositiveIntegerField(null=True, blank=True) available = models.BooleanField(default=True) popular = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) comments = GenericRelation(Comment) class Meta: ordering = ('-created',) def __str__(self): return self.name I add products in admin panel this is the error: