Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django For While Loops and counters when returning data
I am pulling some crypto data into my web app, and placing it into bootstrap cards. My issue is with the number of cards now populating my site. So I thought, no sweat. I'll just initialize a counter at 0 and throw a while loop in there until around 9 or 10. So far no bueno, the code below is the functioning version where it just unloads unlimited crypto cards. I've tried ranges, and If anyone has an idea how I can accomplish this, it'd be greatly appreciated. I don't think it's difficult, just not making the connection. I've even found cases now where you need to register the while loop just to use it in django ? @register.tag('while') had no idea {% for x in api.Data %} <div class="col-sm"> <div class="card-deck"> <div class="card" style="width: 18rem"> <img class="card-img-top" src="{{ x.imageurl }}" alt="{{ x.source }}"> <div class="card-body"> <h5 class="card-title">{{ x.title }}</h5> <p class="card-text">{{ x.body }}</p> <a href="{{ x.url}}" class="btn btn-primary">Learn more</a> </div> </div> </div> <br /> </div> {% endfor %} -
Django populating table in template with two different data sets
I have problem. I need to populate one table with two different sets of data, one is queryset and the other is list. Is there any way to populate table with two sets of data using one {% for %} statement? Something like {% for categories, expenses in categoriesList and expensesList %}. -
Django query to extract values when there is an intermediate table
My database has the following structure. Table1: Name unique_name name_class Table2: Node tid rank path depth Table3: Synonym node (foreignkey to Node) name (foreignkey to Name) I want to extract tid and name based on a condition. I know I can do this names = Synonym.objects.filter(node__path__startswith=path, node__depth__gte=depth, name__name_class="ABC").order_by('node__path') for n in names: print(n.node.tid, n.name.unique_name) How can I make a query to extract tid and name in a single step avoiding the use of for loop ? -
how can i add a JavaScript object to be submitted with my Django form?
I am building a blog with Django and using editorjs as my block editor, the data gets returned as a JSON object, how can I include this object with my Django form? it can be submitted as a string since I am parsing it anyway, I know using an API would solve my issue but I was running into trouble trying to add the images through an API, besides I would like to make use of the built-in class views any help would be greatly appreciated, thanks in advance -
Django CreateView - if field is empty, don't create an object and instead redirect to different view. How do I do this?
I have a media model and a product model. When a user creates a product they first upload a picture and then after this, they're forwarded to the product detail page where they can edit the products attributes. This works fine, however if the user doesn't upload a picture I'd like the program to skip creating a media object and just go straight to the product detail page. I've tried returning a reverse() function from form_valid() but this doesn't work so I'm wondering if anyone knows why this is and how I can fix this? My code currently: class ProductMediaCreate(generic.CreateView): model = ProductMedia fields = ('media',) template_name = 'media/media_create.html' def form_valid(self, form): product_obj = Product.objects.create() if not form.instance.media: return reverse('product_detail', kwargs={'pk': product_obj.pk}) form.instance.product = product_obj return super().form_valid(form) def get_success_url(self): return reverse('product_detail', kwargs={'pk': self.product.pk}) Thanks in advance for any help! - GoingRoundInCircles -
How to order URLs in Django? I am getting `Page Not Found` error because of misplaced urls?
I am getting below error when I want to add a project or go to project_create URL. Page not found (404) Request Method: GET Request URL: http://localhost:8000/project/add/ Raised by: projects.views.project_detail_view the URL says /project/add/ that according to the view it must open project_create_view but the error is raised by detail view projects.views.project_detail_view. This is the URL: path('project/<slug:project_slug>/delete/', project_delete_view, name='project_delete'), path('project/<slug:project_slug>/update/', project_update_view, name='project_update'), path('project/<slug:project_slug>/', project_detail_view, name='project_detail'), path('projects/list/', all_projects_view, name='all_projects'), path('project/add/', project_create_view, name='project_create'), path('administration/', administration, name='administration'), path("", home, name='home'), if I comment this line path('project/<slug:project_slug>/',project_detail_view, name='project_detail'), then project_create URL goes to right view and right template. Why is this happening? I used different name, url and view name. Why is this happening? -
Django: Get count of value in queryset
I am new to Django so I am still learning things. Having difficulty learning how to manipulate QuerySets. I am trying to get the count of a value inside my queryset and would like help knowing how to do so. I have a QuerySet of Review objects that all look like this: Review: { total_score: 100, scores: [{ 'criteria_1': 5, 'criteria_2': 6, 'criteria_3': 7, }] } How would I get the count of all the "criteria_1" scores in this queryset where the value of critera_1 is above 2? -
Google maps autocomplete not working in Django MultiFormView
I'm working with the library django-google-maps to create an address field for properties. For displaying the form, I'm using the following code: class PropertyForm(forms.ModelForm): class Meta: model = Property fields = ['address', 'owned_since', 'geolocation', 'bought_for', 'property_type'] widgets = { 'address': map_widgets.GoogleMapsAddressWidget(attrs={'data-map-type': 'roadmap', 'data-autocomplete-options': json.dumps({ 'componentRestrictions': {'country': 'us'} })}), 'geolocation': forms.HiddenInput(), 'owned_since': forms.DateInput(attrs={ 'placeholder': 'YYYY-MM-DD' }), 'bought_for': CustomMoneyWidget(attrs={'class': 'form-control'}) } It works perfectly in a generic UpdateView and in the admin interface, but when I try to include it in a MultiFormView, the map does not show and the autocomlete isn't working either, it behaves like a simple CharField. There are also no errors or messages in the console. What am I missing here? -
How to keep the data in the form after posting it in Django
I'm new to Django and I need your help with my personal project. I have a couple of forms (numerical, radio, checkbox). After I click the Submit button, I want the entered values to stay there so that if I want to change one value and do further computation using that new value, I don't have to fill entire form again. I figured out a way for numerical fields - I added a value of each inputs equal to the variable collected from the response. I have my form in my base.html that is extended by results.html, hence the form is always visible. views.py def home(request): return render(request, 'home.html', {}) def results(request): if request.method == 'POST': mag_field = (request.POST.get('mag_field')) mms = (request.POST.get('mms')) re = (request.POST.get('re')) fs = (request.POST.get('fs')) diameter = request.POST.get('diameter') qms = request.POST.get('qms') vc_diameter = request.POST.get("vc_diameter") pp_height = request.POST.get("pp_height") overhang = request.POST.get("overhang") context = {"overhang": overhang, "pp_height": pp_height, "vc_diameter": vc_diameter, "mag_field": mag_field, "mms": mms, "re": re, "fs": fs, "diameter": diameter, 'qms': qms} return render(request, 'results.html', context) All inputs are in one form HTML for numeric field <form method="POST" action={% url 'results' %}> {% csrf_token %} <div class="container"> <div class="row"> <div class="col"> <div class="form-group"> <label for="exampleInputEmail1">Magnetic Field</label> <input value="{{ mag_field … -
ModuleNotFoundError - poetry / cookiecutter
I'm trying to run commands through poetry and keep getting this error: Traceback (most recent call last): File "manage.py", line 30, in <module> execute_from_command_line(sys.argv) File "/mnt/c/users/lisa/documents/github/pollsapi_w_template/.venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/mnt/c/users/lisa/documents/github/pollsapi_w_template/.venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/mnt/c/users/lisa/documents/github/pollsapi_w_template/.venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/mnt/c/users/lisa/documents/github/pollsapi_w_template/.venv/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/mnt/c/users/lisa/documents/github/pollsapi_w_template/.venv/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/mnt/c/users/lisa/documents/github/pollsapi_w_template/pollsapi_w_template/users/models.py", line 11, in <module> from pollsapi_w_template.users.emails import RestorePasswordEmail, VerificationEmail File "/mnt/c/users/lisa/documents/github/pollsapi_w_template/pollsapi_w_template/users/emails.py", line 3, in <module> from snitch.emails import TemplateEmailMessage File "/mnt/c/users/lisa/documents/github/pollsapi_w_template/.venv/lib/python3.8/site-packages/snitch/emails.py", line 11, in <module> from snitch.tasks import send_email_asynchronously File "/mnt/c/users/lisa/documents/github/pollsapi_w_template/.venv/lib/python3.8/site-packages/snitch/tasks.py", line 3, in <module> from celery.task import task ModuleNotFoundError: No module named 'celery.task' I'm in the virtual environment created through poetry.toml and I'm trying to run poetry run python manage.py migrate for example. I have tried poetry add celery with the following result: RuntimeWarning: The _posixsubprocess module is not being used. Child process reliability … -
Quando eu faço uma pesquisa em meu blog django e realizo a paginação dos resultados dessa pesquisa ocorre esse erro -->
Essa é minha view --> class Search(ListView): queryset = Post.objects.all() paginate_by = 5 template_name = "search.html" def get_queryset(self): result = super(Search, self).get_queryset() query = self.request.GET.get("q") if query: query_list = query.split() result = result.filter( reduce(operator.and_, (Q(title__icontains=x) for x in query_list)) ) | result.filter( reduce(operator.and_, (Q(content__icontains=x) for x in query_list)) ) return result Esse é o erro Esse erro só ocorre quando eu faço a paginação dos resultados de minha pesquisa, alguém sabe como eu resolvo isso? -
DJANGO API REST ERROR : Class RetrieveUpdateDestroyAPIView has no attribute 'as_view'
i need help. In Django, i want to manage file per class, but i have error. I create folder call views, in this folder i created folder Predicacion, and in this i create file PredicacionRead.py views/Predicacion/PredicacionRead.py from api.serializers.Predicacion.PredicacionSerializer import PredicacionSerializer from api.models import Predicacion from rest_framework.generics import RetrieveUpdateDestroyAPIView class PredicacionRead(RetrieveUpdateDestroyAPIView): queryset = Predicacion.objects.filter().order_by('fecha_publicacion') serializer_class = PredicacionSerializer http_method_names = ['get'] # solo permitimos la creación del producto In url_patterns file urls.py from rest_framework import routers from django.urls import path,include from api.views.Predicacion import PredicacionLista,PredicacionRead route = routers.SimpleRouter() urlpatterns = [ path('predicaciones/<int:pk>/', PredicacionRead.as_view()), ] urlpatterns += route.urls But i have error in runserver: AttributeError: module 'api.views.Predicacion.PredicacionRead' has no attribute 'as_view' But, i i create file views2.py in root folder for module with same content of PredicacionRead, it is work -
How can I make datatables compatible with my theme?
I am using a theme that it's has it's own styling defined based on bootstrap 4.5.0 When I try to use datatables( the bootstrap 4 version ) the theme style breaks badlly. https://datatables.net/ The plugin uses this styling: <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css"/> If I don't add it (because I have the bootstrap theme style already reffered) then the table styling breaks. Not so baddly but enough to encourage me not to use the plugin's bootrstap version at all because the default one looks better. Is there a way to make it work both ? I would reallt like to use the boostrap version of the plugin. Looks and feels much cooler. -
How to make pagination appear?
The pagination isn't showing up at the bottom of my page. And I can't figure why. It's driving me bonkers. I'm user it's a super easy fix, too. The pagination is all bootstrap presets. I have a feeling it has to with the positioning of the {% include... %} on the home.html. Or it could be that I didn't up the include correctly pointing to the correct html file. The pagination.html lives directly in the templates folder. So I think I have written it correctly Views: def home(request): post = Pilot.objects.all().order_by('id') # Pagination PILOTS_PER_PAGE = 15 paginator = Paginator(post, PILOTS_PER_PAGE) # Show 15 pilots per page. page = request.GET.get('page') try: post = paginator.page(page) except PageNotAnInteger: post = paginator.page(1) except EmptyPage: post = paginator.page(paginator.num_pages) context = { 'post': post, #'page': page, } return render(request, 'home.html', context) html: <nav aria-label="Page navigation"> {% if page_has_other_pages %} <ul class="pagination"> {% if page.has_previous %} <li> <a aria-label="Previous", href="?page={{ page.previous_page_number }}">&laquo;</a> </li> {% else %} <li class="disabled"> <span>&laquo;</span> </li> {% endif %} {% for pages in page.paginator.page_range %} {% if page.number == pages %} <li class="active"> <span>{{ pages }}<span class="sr-only">(current)</span></span> </li> {% else %} <li> <a href="?page={{ pages }}">{{ pages }};</a> </li> {% endif %} {% … -
How to replace one field of one model object in Django?
I'm trying to change tags for an object. I first filter for the object I'm looking for and I now don't don't know how to replace the field (usertags). def change_tags(request, pk): file = Uploaded.objects.filter(pk=pk).values('usertags') # file = get_object_or_404(Uploaded, pk=pk) if request.method == "POST": form = ChangeTagsForm(request.POST) if form.is_valid(): print(file) form.save() return HttpResponseRedirect(reverse('index')) else: form = CommentForm() return render(request, 'index.html', {'form': form}) class ChangeTagsForm(forms.ModelForm): class Meta: model = Uploaded fields = ['usertags'] -
Replace href of 'Add Another Row' button in Django admin TabularInline
I have a TabularInline, which allows users to quickly edit certain fields in the Django admin panel. However, when clicking the 'Add Another ...' button, I want to re-direct the user to a new link, instead of adding another row. Here is the code for my TabularInline: class CustomInline(admin.TabularInline): model = CustomModel extra = 0 verbose_name = "Custom Model" fields = ['title', 'pub_date', 'published'] show_change_link = True I've tried to use jQuery to select the relevant element so that I can replace the link's href. However, it doesn't seem to be finding the relevant element. When I inspect the form in Chrome dev tools, I can see the element (screenshot below): However, when I try and select the element using the following jQuery code, I'm getting nothing back. $( document ).ready(function() { let fiveQWGroup = $("div#fiveqw_set-group div.tabular fieldset.module table tbody tr:last-child"); console.log(fiveQWGroup) }); The relevant selector doesn't seem to be appearing in the source code for that page either. So, my question is, how can I change the href of the button to the required href instead? -
Update DataTable with JsonResponse from Django not working properly
I have a Django application and a page where data is written to a table that I am styling using DataTables. I have a very simple problem that has proven remarkably complicated to figure out. I have a dropdown filter where users can select an option, click filter, and then an ajax request updates the html of the table without reloading the page. Problem is, this does not update the DataTable. My html: <table class="table" id="results-table"> <thead> <tr> <th scope="col">COL 1</th> <th scope="col">COL 2</th> <th scope="col">COL 3</th> <th scope="col">COL 4</th> <th scope="col">COL 5/th> </tr> </thead> <tbody class="table_body"> {% include 'results/results_table.html' %} </tbody> </table> results_table.html: {% for result in result_set %} <tr class="result-row"> <td>{{ result.col1 }}</td> <td>{{ result.col2 }}</td> <td>{{ result.col3 }}</td> <td>{{ result.col4 }}</td> <td>{{ result.col5 }}</td> </tr> {% endfor %} javascript: function filter_results() { var IDs = []; var IDSet = $('.id-select'); for (var i = 0; i < IDSet.length; i++) { var ID = getID($(IDSet[i])); IDs.push(ID); } // var data = []; // data = $.ajax({ // url:"filter_results/" + IDs + "/", // dataType: "json", // async: false, // cache: false, // data: {}, // success: function(response) { // $('#results-table').html(response); // // console.log(response.length); // // console.log(typeof response); // … -
How to render one specific data from foreign key using django form
What I want I am trying to build a app where user can book some product from store. I have a foreign key named customer in my Booking model. I want to render only the current logged in customer in the field. Problem The problem is when I try to render customer its grab all the existing customer with drop down. My question is how to filter current logged in customer from customer foreign key. I attached a screenshot Untitled.png Here views.py @login_required(login_url='adminlogin') @allowed_users(allowed_roles=['USER']) def User_Booking(request): #booking = Booking.object.get(id=pk) bookingForm = forms.BookingForm() if request.method == 'POST': bookingForm = forms.BookingForm(request.POST) if bookingForm.is_valid(): booking = bookingForm.save(commit=False) booking.save() return render(request, 'user_booking.html',{'bookingForm':bookingForm}) Here models.py class Booking(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) Package = models.ForeignKey(Package, null=True, on_delete=models.SET_NULL) address = models.CharField(max_length=40, null=True) mobile = models.CharField(max_length=20,null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) status=models.BooleanField(default=False) def __str__(self): return self.customer.get_name Here user_booking.html <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> {% render_field bookingForm.customer class="form-control"%} <div class="invalid-feedback"> Please enter your shipping address. </div> </div> <div class="mb-3"> {% render_field bookingForm.Package class="form-control"%} <div class="invalid-feedback"> Please enter your shipping address. </div> </div> <div class="mb-3"> {% render_field bookingForm.address class="form-control" placeholder="Address"%} <div class="invalid-feedback"> Please enter your shipping address. </div> </div> <div class="mb-3"> {% render_field bookingForm.mobile class="form-control" placeholder="Mobile" … -
How to verify a token using Google OAuth in DRF from JOOMLA server
enter image description here How to verify a token using Google OAuth in DRF from JOOMLA server? Anyone have idea about this.. -
Issue in django squashed migration while migrating the app from django 1.11 to django 3.0
The app was running on 1.11. we are migrating it to 3.0. As it is a multi-tenanted system we use django-tenant-schema. Consider the app is running on django 1.11, I ran django migrate_schemas command, it ran all the migrations, Then I switch to different virtualenv where django 3.0 is installed but here the showmigrations command says below migration hasn't run 0023_auto_20180921_1708_squashed_0025_auto_20180921_1727 It should be same in both django versions, isn't it? In screenshot, left side is django 3.0 and right side is django 1.11 -
How to append a queryset into a list?
The error I am getting is AttributeError: 'QuerySet' object has no attribute '_meta' What I am trying to do is to get the VAttribute Objects related to given class and the AttributeValues related to PAttribute object and convert into a list ? class_id = request.GET.get('class_id') print(class_id) qs = VAttribute.objects.filter(class=class_id) print(qs, '') attribute_data = [] attribute_data_values = [] for obj in qs: attribute_data.append(obj.attribute) attribute_data_values.append(obj.attribute.attributevalues_set.all()) # the problem is here data = serializers.serialize('json', attribute_data) values = serializers.serialize('json', attribute_data_values) data = { 'attribute': data, 'values': values } return JsonResponse(data, safe=False) These are my models class VAttribute(models.Model): class = models.ForeignKey(Class, on_delete=models.CASCADE) attribute = models.ForeignKey(PAttribute, on_delete=models.CASCADE) attribute_values = models.ManyToManyField(AttributeValues) class PAttribute(models.Model): name = models.CharField(max_length=255, unique=True) class AttributeValues(models.Model): name = models.CharField(max_length=255) attribute = models.ForeignKey(PAttribute, on_delete=models.CASCADE) -
Getting cannot resolve keyword when using django filter
I'm getting this error when I'm filtering csv output by date. And I also want to ask how to output a data to csv from last mont or past 6 months? as I only have current_month & current_year Thanks! Cannot resolve keyword 'created_at' into field. Choices are: amount, id, level, report, timestamp @models.py class Rainfall(models.Model): level = models.CharField(max_length=10, blank=True, default='') amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) @views.py def export_by_month(request): response = HttpResponse(content_type='text/csv') current_month = datetime.now() writer = csv.writer(response) writer.writerow(['Level', 'Amount', 'Timestamp']) for i in Rainfall.objects.filter(created_at__month=current_month): writer.writerow(i) response['Content-Disposition'] = 'attachment; filename="rainfall.csv"' def export_by_year(request): current_year = datetime.now().year return Rainfall.objects.filter(created_at__year=current_year) -
facing a weird bootstrap behavior in chrome
I have a django-bootstrap project in which an html page has a dynamically generated table with data-toggle popovers on td elements. in firefox, opera and edge everything works perfectly fine and the popover show up, but in chrome they just don't. however when I copy paste the same code in a new blank html test page unrelated to the project it works (minus a few css issues for the rest of the page). am really out of my wits end trying to understand the behavior I tried: emptying cache and hard reload multiple time no success forcing the state to trigger popover no success no errors/warnings showing up in console restart server and dev machine no success clear a week's worth of cache and browser history check if there is a chrome extension blocking it. (none am aware of since the test page is working fine) made sure my jquery bootstrap 4 cdn's are up to date I really have no clue what to turn to to find the source of the behavior. what steps do you do you guys go through if an element is randomly not showing on your page or you going through unexpected behaviors -
Django No module named 'responsive_images'
Getting the following error when ported Django from 2.7 to 3.6 Traceback (most recent call last): File "manage.py", line 21, in <module>main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Django\CampusStore\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Django\CampusStore\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Django\CampusStore\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Django\CampusStore\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Django\CampusStore\venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Program Files (x86)\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'responsive_images' -
Why is this if statement not working in Django?
I'm just trying to run an if statement in html using django in the {% %} things. The statemnet is {% if listing in watchlist %}. Even though the listing is in watchlists, it doesn't make the if statement true. I used {{ }} to see what watchlist and listing are. for {{ watchlist }} I got: <QuerySet [<Watchlists: 15: Dan1308 has added 3: The Bus (yes the cool airplane), starting at 3000 to watchlist>]> for {{ listing }} I got: 3: The Bus (yes the cool airplane), starting at 3000 here's my views.py: def listing(request, NewListings_id): user = request.user listing = NewListings.objects.get(pk=NewListings_id) comments = Comments.objects.filter(listing=listing) watchlist = Watchlists.objects.filter(user=user) return render(request, "auctions/listing.html", { "listing": listing, "comments": comments, "user": user, "watchlist": watchlist }) and here's my models.py: class Watchlists(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) listing = models.ForeignKey(NewListings, on_delete=models.CASCADE) def __str__(self): return f"{self.id}: {self.user} has added {self.listing} to watchlist" So, why is it not working?