Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Project Directory Structure
in my django project structure, i want all my django apps in a separate Apps Folder, but when i include it in settings.py it raises an error, raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'TestApp'. Check that 'Apps.TestApp.apps.TestappConfig.name' is correct. INSTALLED_APPS = [ ... 'Apps.TestApp' ] But when i only include TestApp, i raises no module named 'TestApp' Error. INSTALLED_APPS = [ ... 'TestApp' ] -
keep getting Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. error
I want to implement password reset functionality on my web page but I am getting NoReverseMatch at /accounts/password_reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. error. please help me to solve this error url.py Code: app_name="accounts" urlpatterns=[ path('password_reset/', auth_views.PasswordResetView.as_view(template_name="password_reset.html",success_url=reverse_lazy('accounts:password_reset_done')), name='password_reset'), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password_reset_confirm.html",success_url=reverse_lazy('accounts:password_reset_complete')), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="password_reset_done.html"), name="password_reset_complete"), ] passwrd_reset.html {% extends 'base.html' %} {% block title %}Password Reset Page{% endblock %} {% load crispy_forms_tags %} {% block body %} <div class="container"> <div class="row mt-5 pt-3"> <div class="col-md-8 offset-md-2"> <div class="card my-3 shadow"> <div class="card-body"> <h4>Password Reset Page</h4> <hr> <div class="alert alert-info"> Enter email and a mail will be sent with instructions to reset password </div> <form method="POST"> {% csrf_token %} {{ form|crispy }} <input class="btn btn-primary btn-block" type="submit" value="Reset Password"> </form> <hr> </div> </div> </div> </div> {% endblock body%} -
How to add dynamically add apps in install apps in django settings.py by using apps.py of app directory?
I am trying to add app automatically after python manage.py startapp command in installed app in django-settings.py file. -
Django queryset to show values every month
I'm making a Django APP (required) to calculate every month the profits and losses. There's a feature that I wanted to put that in N months you'll be paying the value/N (i.e: $100/5 that equals to $20 per month). This feature would be like a Bank APP shows how many you have yet to pay (i.e: from this month to October) By the way, there's only one record from the losses (I'm trying not to change this) So far so good, but the record appear only in the month of my search (view below) and when I try to use: Account.objects.filter(date__year__gte=y) or Account.objects.filter(date__month__gte=m) or Account.objects.filter(date__year__lt=y) or Account.objects.filter(date__month__lt=m) The record shows the entire year or the months whose are greater or less than the month saved (with no filter, so if it's from July to November, it'll show until December or in January) View.py def account(request, pk): search = f"{datetime.now().year} - {datetime.now().month:02}" account = Account.objects.get(id=pk) ctx = { 'search': search } if request.GET.get('month'): search = request.GET.get('month') y, m = search.split('-') ctx.update({ 'search': search }) date_loss = filter_by_model_date(Loss, m, y) date_profit = filter_by_model_date(Profit, m, y) profit = filter_by_account(date_profit, account) loss = filter_by_account(date_loss, account) ctx.update({ 'profit': profit, 'loss': loss }) return render(request, 'account/account.html', … -
Send data to html and get choose part it back in the same views
I work on api weather project and by POST i send from website city name to views and I send back like possible locations (like "name" London have more than one city). I want choose one and send this one back to my view and in the same view still works on it (if is one location by coords we miss this stage). Code: cities_locations = [] if request.method == 'POST': form = CityForm(request.POST) if form.is_valid(): new_add_city = form.cleaned_data['name'] get_location_for_new_city = get_city_location(new_add_city) if len(get_location_for_new_city) == 1: pass #If is one location only else: for counter_cities in range(len(get_location_for_new_city)): city_location = { 'city': new_add_city, 'lat': get_location_for_new_city[counter_cities]['lat'], 'lon': get_location_for_new_city[counter_cities]['lon'], 'country': get_location_for_new_city[counter_cities]['country'], 'state': get_location_for_new_city[counter_cities]['state'], 'number': counter_cities, } cities_locations.append(city_location) print(cities_locations) form = CityForm() context = { 'cities_locations': cities_locations, 'form': form, } return render(request, 'weatherapp/yourweather.html', context) Can you help me with an example or some tips? Thank you for help. -
Pass the data to python script from frontend and fetch it back
Let's say I have trivial x and y variables (user input in frontend made in vue, Javascript) and we need to pass it to the python Script, which will return the result of calculation, let's say: Sum of x+y =... Multiplication of x*y = ... I know how to return these calculations either to the terminal output either to the file. Is there an easier way to use some API to read the response of the python script and show it on frontend to the user? Current system is: Frontend: vue Backend: Django with REST API. -
How do you select a particular object from a django model and use it to retrieve a url? (CS50 Project 2)
I am doing CS50 Project 2 and have a django model called Listing that has an object called Category that the user can pick using a dropdown list. All the categories are listed on the categories page and need to link to the categories_page page that displays all the listings in that category. Can you help me with the href and variable for the categories page to link it to the categories_page page? categories views.py def categories(request): return render(request, "auctions/categories.html",{ "Miscellaneous": Listings.objects.all().filter(category=Miscellaneous) }) categories.html (I need to link all the categories on this page to their own categories_page.) {% block body %} <h1>Categories</h1> <a href="{% url 'categories' Miscellaneous.category %}" style = "color: rgb(58, 58, 58);"><h5>Miscellaneous</h5></a> <h5>Movies and Television</h5> <h5>Sports</h5> <h5>Arts and Crafts</h5> <h5>Clothing</h5> <h5>Books</h5> {% endblock %} categories_page views.py def categories_page(request, category): listings = Listings.objects.all().filter(category=category) return render(request, "auctions/categories_page.html",{ "listings": listings, "heading": category }) categories_page.html {% block body %} <h1>{{ heading }}</h1> {% for listing in listings %} <a href="{% url 'listing' listing.id %}" style = "color: rgb(58, 58, 58);"> <img src ="{{ listing.image }}" style = "height: 10%; width: 10%;"> <h4 class = "text">{{ listing.title }}</h4> <h6>Description: {{ listing.description }}</h6> <h6>Category: {{ listing.category }}</h6> <h6>Price: ${{ listing.bid }}</h6> </a> {% … -
whats the correct way of using get_or_create with django?
how can it be that get_or_create results in: pymysql.err.IntegrityError: (1062, "Duplicate entry '...blabla' for key 'descriptor'") please have a look on how i call get_or_create: for key in keys: files_obj, created = Files.objects.get_or_create(file_path=key, file_name=Path(key).name, libera_backend=resource_object) if created: files_obj_uuids.append(files_obj.pk) resource_objects.append(resource_object.pk) thanks in advance -
(help) Django: no such table: users_company
i was trying to create a user's company profile but i got the following error: OperationalError at /admin/users/company/ Exception Value: no such table: users_company I think theres something wrong in my user' model.py because when i try to make migrations myapp> it shows No changes detected in app model.py: class Company(models.Model): name = models.CharField(max_length=100) about = models.TextField(gettext_lazy('about'), max_length=500, blank=True) role = models.CharField(max_length=100) address=models.CharField(max_length=100) contact=models.CharField(max_length=100) def __str__(self): return f'{self.user.username} Company' Does anyone can help me with this? I am new to django, lmk if you need any other information. Thanks ! -
How to automatically create subdomains after creating a tenants in Django on digital ocean
Please i have created a droplet in digital ocean. the project is a SaaS project which the user can create a subdomain for them automatically. when the sub domain is created, it is not recognize on the server. unless i go and add a subdomain in digital ocean. is there a way to create a sub domain without creating it at domain panel at the digital ocean dashboard -
How to set default size to photos in ckeditor container
So i am using ckeditor in my django project and i want to set the default size to the photos that i drag and drop into the ckeditor container because currently the photos are too big and it looks ugly. I would like them to be fixed 400px and not their original size. -
How to apply an arbitrary filter on a specific chained prefetch_related() within Django?
I'm trying to optimize the fired queries of an API. I have four models namely User, Content, Rating, and UserRating with some relations to each other. I'm going to the respective API to respond all of the existing contents alongside their rating count as well as a the score of given by a specific user to that. I used to do something like this: Content.objects.all() as a queryset but I realized that in the case of the huge amount of data tons of query will be fired. So I've done some efforts to optimize the fired querie using select_related and prefetch_related. However I'm dealing with an extra python searching that I hope remove that by a controlled prefetch_related() — applying a filter just for a specific prefetch in a nested prefetch and select. Here are my models: from django.db import models from django.conf import settings class Content(models.Model): title = models.CharField(max_length=50) class Rating(models.Model): count = models.PositiveBigIntegerField(default=0) content = models.OneToOneField(Content, on_delete=models.CASCADE) class UserRating(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE ) score = models.PositiveSmallIntegerField() rating = models.ForeignKey( Rating, related_name="user_ratings", on_delete=models.CASCADE ) class Meta: unique_together = ["user", "rating"] Here's what I've done so far: contents = ( Content.objects.select_related("rating") .prefetch_related("rating__user_ratings") .prefetch_related("rating__user_ratings__user") ) for c … -
Why is only the first React component rendering in my multi-page in Django app?
I am trying to render a secondary component to a different URL in my React frontend of my Django app. The URLs seem to be set up correctly, as the page title is changing accordingly and no errors are thrown, but the page itself is blank. My components are being loaded by importing in index.js in the components directory. #index.js import App from './components/App'; import Viz from './components/Viz'; #urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), path('viz/', views.getviz) ] For the simplicity of testing, I made the components a copy so I know it works. // App.js import React, { Component, Fragment } from 'react'; import ReactDOM from 'react-dom'; import Header from './layout/Header'; import Dashboard from './splits/Dashboard'; import Alerts from './layout/Alerts'; import { Provider } from 'react-redux'; import { Provider as AlertProvider } from 'react-alert'; import AlertTemplate from 'react-alert-template-basic'; import store from '../store'; //Alert Options const alertOptions = { timeout: 3000, position: 'bottom center' } class App extends Component { render() { return ( <Provider store={store}> <AlertProvider template={AlertTemplate} {...alertOptions}> <Fragment> <Header /> <Alerts /> <div className="container"> <Dashboard /> </div> </Fragment> </AlertProvider> </Provider> ); } } ReactDOM.render(<App />, document.getElementById('app')) The only difference with the other … -
How to use media files during deployment (django)?
Need help with managing media files during deployment. I've read several articles and documentation regarding to subject, but can't fix my particular site: tis, this and django documentation. Guess I've missed some obvious thing, or it could be misprint in code (link to media files). So, I've deployed site on django, using gunicorn and nginx. When users download some picture on site it save in media directory. models.py class News(models.Model): title = models.CharField(max_length=128) content = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True) settings.py DEBUG = False ... STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media/' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('news/', include('news.urls')), ... ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Try to add urlpatterns = [...]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) but it doesn't work for me. I guess it could be some problem in pass to media file. I've checked link in page - it's correct. <img src="photos/2022/05/10/kitten.jpg"> And this file is there. Can't download picture on page. How to download and use media files correct? I'll be glad to get advice or link to any documentation regarding to this subject. Thank you in advance. -
Django Blog - edit/delete user comments functions help needed pls
I am quite new to software development and quite new to django and python. I am currently working on a project to develop blog, which needs to have functions for users to edit and delete their own comments. Whilst I have developed the blog, I am struggling with getting the functions correctly coded and wired up to URLS file. I have added icons below user comments to either delete or edit their comments. My question is what is the correct code for creating functions in views file and also how can i correctly wire it up to URL file. I am not sure if I am missing any packages to get the edit/delete functionality developed. I have enclosed details of my model, views and urls files. Any guidance/support will be highly appreciated. Models file from django.db import models from django.contrib.auth.models import User from cloudinary.models import CloudinaryField STATUS = ((0, "Draft"), (1, "Published")) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts") updated_on = models.DateTimeField(auto_now=True) content = models.TextField() featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) likes = models.ManyToManyField(User, related_name='blog_likes', blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return … -
Reverse for 'add_comment' with keyword arguments '{'pk': ''}' not found. 2 pattern(s) tried:
This question searching internet for a week but i can't fix it Error_Message Reverse for 'add_comment' with keyword arguments '{'pk': ''}' not found. 2 pattern(s) tried: ['shopping_mall/top_cloth/(?P<pk>[0-9]+)/comment\\Z', 'top_cloth/(?P<pk>[0-9]+)/comment\\Z'] Error_60 line <a class="btn btn-success" href="{% url 'add_comment' pk=product.pk %}">add comment</a> MY urls urlpatterns = [ path('', views.index, name='index'), path('top_cloth/', views.top_cloth), path('top_cloth/<int:pk>/', views.cloth_detail, name='top_cloth_pk'), path('top_cloth/<int:pk>/comment', views.add_comment, name='add_comment'), path('top_cloth/<int:pk>/remove/', views.comment_remove, name='comment_remove'), path('top_cloth/<int:pk>/modify/', views.comment_modify, name='comment_modify'), ] My views def cloth_detail(request, pk): post = ProductList.objects.get(pk=pk) product = Comment.objects.order_by() return render( request, 'shopping_mall/cloth_detail.html', { 'post': post, 'product': product } ) def add_comment(request, pk): product = get_object_or_404(ProductList, pk=pk) if request.method == "POST": form = CommentFrom(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.product = product comment.save() return redirect('index', pk=product.pk) else: form = CommentFrom() return render(request, 'shopping_mall/add_comment.html', {'form':form}) Traceback Request Method: GET Request URL: http://127.0.0.1:8000/shopping_mall/top_cloth/1/ Django Version: 4.0.4 Python Version: 3.9.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'crispy_forms', 'shopping_mall', 'single_pages', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'django_summernote'] Installed 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'] Template error: In template D:\github\kys-shoppingmall\shopping_mall\templates\shopping_mall\cloth_detail.html, error at line 60 Reverse for 'add_comment' with keyword arguments '{'pk': ''}' not found. 2 pattern(s) tried: ['shopping_mall/top_cloth/(?P<pk>[0-9]+)/comment\\Z', 'top_cloth/(?P<pk>[0-9]+)/comment\\Z'] 50 : {{ comment.text|linebreaks }} 51 : </p> 52 : </dlv> 53 : {% endif %} … -
How to properly catch fetch request in django
I started studying django. I have js code that calls fetch when I click the button button = document.querySelector('.button') button.addEventListener('click', function(){ fetch('http://127.0.0.1:8000/test_fetch/', { method: 'GET', headers: { 'Content-Type': 'application/json', "X-Requested-With": "XMLHttpRequest", "HTTP_X_REQUESTED_WITH": "XMLHttpRequest" } }) }) <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button class="button">hello</button> {{ ajax }} <script src="{% static 'train_app/js/test_fetch.js' %}"></script> </body> class TestFetch(TemplateView): template_name = 'train_app/test_fetch.html' def get(self, request): ajax = request.headers data = { 'name': 'Yura', 'age': 20, 'list': [1,2,3,4], 'ajax': ajax } return render(request, self.template_name, context=data) I tried to catch the fetch request using request.META and request.headers. But they return to me information only about the first get request which is caused through urls.py. How do I get information that this was a fetch request and its Content-Type attribute. -
How to construct nested QuerySet with django ORM?
How can construct the JSON format I expect with just QuerySet? Use Prefetch or Subquery? Only use QuerySet, I don't want change JSONField or serializer. models: class Product(models.Model): name = models.CharField(max_length=128, ) product_attr = models.ManyToManyField("ProductAttr", through="ProductBindAttr", ) class ProductAttr(models.Model): attr_name = models.CharField(max_length=128, unique=True, ) class ProductBindAttr(models.Model): class Meta: UniqueConstraint("product", "attr_key", "attr_value", name='unique_bind_attr') product = models.ForeignKey("Product", on_delete=models.CASCADE, ) attr_key = models.ForeignKey("ProductAttr", on_delete=models.CASCADE, ) attr_value = models.CharField(max_length=128, ) serializers: class ProductBindAttrNestedSerializer(serializers.ModelSerializer): class Meta: model = ProductBindAttr fields = ('attr_value', 'product') product = serializers.StringRelatedField() class ProductGroupByBindAttrSerializer(serializers.ModelSerializer): class Meta: model = ProductAttr fields = ("attr_name", "attr_values") attr_values = ProductBindAttrNestedSerializer(many=True, source="productbindattr_set") views: class ProductGroupByBindAttrViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = ProductAttr.objects.all() # how can I just change `queryset` to do that? serializer_class = ProductGroupByBindAttrSerializer json: [ { "attr_name": "Height", "attr_values": [ { "attr_value": "13 cm", "products": { "name": "G304" } }, { "attr_value": "13 cm", "products": { "name": "G305" } }, { "attr_value": "14 cm", "products": { "name": "G306" } } ] } ] The result I expect: [ { "attr_name": "Height", "attr_values": [ { "attr_value": "13 cm", "products": { "name": "G304", "name": "G305", // I want to merge products which same `attr_value` } }, { "attr_value": "14 cm", "products": { "name": "G306" } } ] } ] -
Cannot use None as a query value error when i try to view page without search query
I have a working search form in my base.html but when itry to access the listing page without passing a search query i get a "Cannot use None as a query value" error. views.py def listing(request): if request.method == 'GET': search = request.GET.get('search') propertys = Paginator(Property.objects.filter(property_name__icontains =search).order_by('-listed_on'), 2) page = request.GET.get('page') propertys = propertys.get_page(page) nums = "p" * propertys.paginator.num_pages return render(request,"listing.html",{"propertys":propertys, "nums": nums, 'search':search}) else: p = Paginator(Property.objects.order_by('-listed_on'), 2) page = request.GET.get('page') propertys = p.get_page(page) nums = "p" * propertys.paginator.num_pages return render(request,"listing.html", {"propertys":propertys, "nums": nums}) -
Object of type Modul is not JSON serializable while trying to set the value of another model in the session
i am trying to save the id of a created model in the session so i can update it later in anothe page, but the set function shows me an error i am using request.session['ORDER'] = serializers.serialize('json', Order.objects.all()) right now but i also used request.session['ORDER'] = order.id, i got the same error if form.is_valid(): if(form.cleaned_data['paymentmethod'] == "PayPal"): print("Paypal choosed") first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] address = form.cleaned_data['address'] zipcode = form.cleaned_data['zipcode'] place = form.cleaned_data['place'] paymentmethod = 'pypnt' order = checkout(request, first_name, last_name, email, address, zipcode, place, phone, cart.get_total_cost(), paymentmethod) print(order.id) print(order) request.session['ORDER'] = serializers.serialize('json', Order.objects.all()) return redirect('cart:process') this is the Order Model lass Order(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.CharField(max_length=100) address = models.CharField(max_length=100) zipcode = models.CharField(max_length=100) place = models.CharField(max_length=100) phone = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) paid_amount = models.DecimalField(max_digits=8, decimal_places=2) vendors = models.ManyToManyField(Vendor, related_name='orders') id = models.AutoField(primary_key=True) class paymentmethod(models.TextChoices): the error: Internal Server Error: /de/cart/ raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Product is not JSON serializable -
class FormularioAlumno(forms.ModelsForm): AttributeError: module 'django.forms' has no attribute 'ModelsForm'
Estoy realizado el proyecto de una pagina web y al momento de correr el programa me sale ese error y no he podido solucionarlo agradecería mucho una pronta solución, ahí adjunte los codigos que me sacan el error del modulo gracias from django.urls import path from Models.Alumno.views import FormularioAlumnoView from Views.HomeView import HomeView urlpatterns = [ #path('admin/', admin.site.urls), path('', HomeView.home, name='home'), path('pagina/', HomeView.pagina1, name='pagina1'), path('pagina2/<int:parametro1>', HomeView.pagina2, name='pagina2'), path('pagina3/<int:parametro1>/<int:parametro2>', HomeView.pagina3, name='pagina3'), path('formulario/', HomeView.formulario, name='formularioprueba'), path('registrarAlumno/', FormularioAlumnoView.index, name='registrarAlumno'), path('guardarAlumno/', FormularioAlumnoView.procesar_formulario(), name='guardarAlumno') ] from django.http import HttpResponse from django.shortcuts import render from Models.Alumno.forms import FormularioAlumno class FormularioAlumnoView(HttpResponse): def index(request): alumno = FormularioAlumno return render(request, 'AlumnoIndex.html', {'form': alumno}) def procesar_formulario(request): alumno = FormularioAlumno if alumno.is_valid(): alumno.save() alumno = FormularioAlumno return render(request, 'AlumnoIndex.html', {'form': alumno, 'mensaje': 'ok'}) from django import forms from Models.Alumno.models import Alumno class FormularioAlumno(forms.ModelsForm): class Meta: model = Alumno fields = '__all__' widgets = {'fecha_nacimiento': forms.DateInput(attrs={'type': 'date'})} -
get sum based on another field django
I have these models: status_choices = ['not received', 'received'] class Investment(Model): # Offering offering = models.ForeignKey(Offering, blank=False, null=False, on_delete=models.CASCADE) invested = models.DecimalField(max_digits=9, default=0, decimal_places=2, blank=True, null=True) status = models.CharField(max_length=200, choices=status_choices, blank=True, null=True, default='not received') class Offering(Model): ... I want to make a property to display the sum of all investments inside the Offering model. I did so like this: @property def amount_invested(self): return Investment.objects.filter(offering_id=self.id).aggregate(Sum('invested'))['invested__sum'] or 0 But, I also want to display the amount_invested iff the status inside the Investment model is 'received'. May I know how I should be able to do this? -
Django project to display multiple styles, one at a time
I have a project in Django. One of the pages uses a ui selector, that is to say, clicking a button changes the style displayed. The button is implemented using javascript. It is done such that there are two divs both initially hidden: <div class="c2" style="display: none"> content </div> <div class="c3" style="display: none"> content </div> The code within those divs uses Django commands to iterate over the same stuff. However, switiching to the second style (I tested putting each div first and it is always the second div) displays a page without all the data that is iterated over again. How does one fix that? -
Difference between User models
I'm learning django now, watch tutorials. The questions is: What is the difference between using: from django.contrib.auth import get_user_model User = get_user_model() User = get_user_model() and from django.contrib.auth.models import User I've seen both of them and both of them used in model with ForeignKey, but I don't know the difference between these two model, for example: author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='posts' ) title = models.CharField(max_length=100) text = models.TextField()``` -
Django rest framework datatables foreign key data could not be obtained
My problem here is when i add a foreign key to my table i face issues like not getting value and not filtering the table below i share the models and serializers. class Foo(models.Model): name = models.CharField(max_length=77, unique=True) phone = models.CharField(max_length=40, null=True, blank=True) email = models.CharField(max_length=80, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.name}" class Process(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) class ProcessSerializer(serializers.ModelSerializer): class Meta: model = Process fields = '__all__' <th data-data="foo.name" data-name="foo.name">Kisi</th> I am adding a foreign key to my model then utilize djangorestframework-datatables package i can not get the name attribute i just get an id like "1" for the foreign key and after adding .name to the foo model in data-data i could not get any value. I get the following error DataTables warning: table id=processes - Requested unknown parameter 'foo.name' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4 I don't see any problem in the code any help is appreciated.