Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i want to show category wise product and paginate
I want to show category wise product and must be in paginate but its not working . i try to do this but I don't know why its not working. Here I have allProducts variable I tried to assign the paginate class but I think I am doing this in correct way maybe but its now working please give me solution for this Here is my Views.py def get(self, request): cart = request.session.get('cart') if not cart: request.session['cart'] = {} #products = None products = Product.objects.all() catsProduct = Product.objects.values("category") cats = {item["category"] for item in catsProduct} allProducts = [] for cat in cats: prods = Product.objects.filter(category=cat) allProducts.append(prods) allProducts = Product.get_all_products() paginator = Paginator(allProducts, 12) page_number = request.GET.get('page') allProducts = paginator.get_page(page_number) cats = Category.get_categories() brands = Brand.get_brands() sliders = Slider.objects.all() offers = Offer.objects.all() categoryID = request.GET.get('category') brandID = request.GET.get('brand') if categoryID: # products = Product.get_products_by_category(categoryID) products = products.filter(category__id=categoryID) # else: # products = Product.get_all_products() if brandID: # proucts = Product.get_brands_by_products(brandID) products = products.filter(brand__id=brandID) # else: # products = Product.get_all_products() # print(request.session['customer']) args = { 'products': products, 'cats': cats, 'brands': brands, 'sliders': sliders, 'offers': offers, 'allProducts':allProducts } return render(request, 'Home/index.html', args) -
How to get a detailed overview of some articles
import React from 'react'; import axios from 'axios'; import { Card } from 'antd'; class ArticleDetail extends React.Component { state = { article: {} } componentDidMount() { const articleID = this.props.match.params.articleID; axios.get(`http://127.0.0.1:8000/api/${articleID}`) .then(res => { this.setState({ article: res.data }); }) } render() { return ( <div> <Card title={this.state.article.title}> <p>{this.state.article.content}</p> </Card> </div> ) } } export default ArticleDetail; -
Django: Execute code only for `manage.py runserver`, not for `migrate`, `help` etc
We are using Django as backend for a website that provides various things, among others using a Neural Network using Tensorflow to answer to certain requests. For that, we created an AppConfig and added loading of this app config to the INSTALLED_APPS in Django's settings.py. This AppConfig then loads the Neural Network as soon as it is initialized: settings.py: INSTALLED_APPS = [ ... 'bert_app.apps.BertAppConfig', ] .../bert_apps/app.py: class BertAppConfig(AppConfig): name = 'bert_app' if 'bert_app.apps.BertAppConfig' in settings.INSTALLED_APPS: predictor = BertPredictor() #loads the ANN. Now while that works and does what it should, the ANN is now loaded for every single command run through manage.py. While we of course want it to be executed if you call manage.py runserver, we don't want it to be run for manage.py migrate, or manage.py help and all other commands. I am generally not sure if this is the proper way how to load an ANN for a Django-Backend in general, so does anybody have any tips how to do this properly? I can imagine that loading the model on startup is not quite best practice, and I am very open to suggestions on how to do that properly instead. However, there is also some other code … -
Postgres table join with a Django generic foreign key
I want to perform a table join in Postgres (9.5) where the name of the second table is a dynamic value taken from columns of the first table (a Django generic foreign key). The JOIN query below to django_content_type allows me to obtain the name of the table I want to join my_table to. SELECT CONCAT(ctype.app_label, '_', ctype.model) AS table_name FROM my_table JOIN django_content_type ctype ON my_table.source_type_id = ctype.id; What I now want to do is extend this query to join my_table with the corresponding source_table for that row. Something like the following: WITH source_table AS ( SELECT CONCAT(ctype.app_label, '_', ctype.model) AS table_name FROM my_table JOIN django_content_type ctype ON my_table.source_type_id = ctype.id LIMIT 1 ) SELECT * FROM my_table JOIN format('%I', source_table.table_name) source ON my_table.source_id = source.id LIMIT 1; Given that this is a generic foreign key relationship it is fine if it is only possible to do this for a single my_table row at a time, ensuring that my_table is only ever joined to a single additional table via the generic foreign key relationship. -
Django Vue.js How to Handle Database Transactions Properly
I am building a web application with Django and Vue.js where you enter some data on the Vue.js frontend and can then trigger a push into the database. Two separate objects will be created and two post-queries will be executed by axios. I want the database to rollback the first query should the second one fail. As far as I can tell, I need to execute both queries and commit the result to the database only if both succeeded, unfortunately I do not know how to handle this situation with the frameworks I am using. Can anyone provide any insight into how to go about doing this? -
Unable to send a PUT request to a Django REST API using Reactjs fetch() method
I've recently started learning Reactjs & made a simple Todo react appplication in order to learn it bit-by-bit, step-by-step.The data in this Todo react front-end is coming from a simple Todo Django REST API. But the problem is I want to change the state of "completed" to depict a task completed. Im trying to do this by sending a PUT request to the API using the unique "id" but getting some errors. Below is my approach : List.js import React from 'react' import Todo from './Todo' import Nav from './Nav' //Class based Component class List extends React.Component { constructor() { super() this.state = { todos: [], } this.handleChange = this.handleChange.bind(this) } fetchData() { fetch('http://localhost:8000/Todo-api/') .then(response => response.json()) .then((data) => { this.setState({ todos: data }); }); } componentDidMount() { this.fetchData(); } handleChange(id) { this.setState(prevState => { const updatedData = prevState.todos.map(todo => { if (todo.id === id) { todo.completed = !todo.completed } return todo }) return { todos: updatedData } }) fetch(`http://127.0.0.1:8000/Todo-api/${id}/?format=json/`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Accept' : 'application/json', // Other possible headers }, body: JSON.stringify(this.state) }).then(function (response) { return response.json(); }).then(function (data) { console.log("Data is ok", data); }).catch(function (ex) { console.log("parsing failed", ex); }); } currentDate() { return … -
Inheritance in class based views
I am currently working on my first website and I'm working with class-based views because I've been told their inheritance is outstanding. Here's the code so you can make yourselves an idea of what I'm trying to do before I tell you the error I'm having. class TranslatorView(View): def translate_amino(self, codon): return self.amino_mapper.get(codon, "") def build_protein(self, phrase): protein = [] i = 0 while i < len(phrase): codon = phrase[i: i + 3] amino = self.translate_amino(codon) if amino: protein.append(amino) else: print(f"The codon {codon} is not in self.mapper_1") i += 3 return protein def error_1(self, request): amino_1= self.build_protein if len(amino_1) % 3: messages.error(request, "DNA chain must be divisible by 3") return redirect('/') Basically, what I'm trying to do is to inherit the function build_protein to the def error_1. Specifically, I want to inherit the phrase parameter in the error_1 def so that the message error appears. However, it appears it's not inheriting anything at all. -
Django 3.1+: has background_task become obsolete?
With Django 3.1 finally supporting async views, has the library "Django Background Task" (pip install django-background-tasks) become obsolete? I have been using it extensively for time consuming, overnight tasks. Do you advice to migrate them? Recommendations or pitfalls? -
How to stop loading the page after clicking on an href link in html?
so this code <a href="" onclick="alert('ITEM ADDED TO WATCHLIST')">Add to your watchlist</a> When i click on the link, an alert pops up from the upper side and when i clicks the OK button, it reloads the page .I want it, not to reload the page after clicking and just stays right where the page currently is. -
django Cast function always sets UTC timezone
When I use: annotate(new_datetime=Cast( TruncHour('old_datetime) + timedelta(days=1), output_field=DateTimeField() )) TruncHour return a datetime in my timezone and after Cast, new_datetime's value will be in my timezone but with UTC tzinfo. How can I set custom tzinfo for Cast function in this case? -
ValueError: Cannot assign must be an instance in Django
I am new to django and I'm trying to insert some data into the database through a form but I am getting an error while inserting the data. How can I solve this issue? I have these models which are connected together: models.py class Major(models.Model): major_cd = models.IntegerField(primary_key=True) description = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'major' class Percentages(models.Model): # major_cd = models.IntegerField(primary_key=True) major_cd = models.OneToOneField( Major, on_delete=models.CASCADE, primary_key=True, db_column='major_cd' ) perc = models.FloatField() class Meta: managed = False db_table = 'percentages' this is my from: per.html <form id="addPercentage" action=""> <div class="form-group row"> <div class="form-group col-md-2"> <input class="form-control" type="number" name="major_cd" placeholder="Major Code" required min=1000 max=9999> </div> <div class="form-group col-md-2"> <input class="form-control" type="number" name="perc" placeholder="Percentage" required> </div> </div> <div class="form-group col-md-2" style="padding-right: 2%;"> <button class="btn btn-info form-control" type="submit">ADD</button> </div> </form> script: $("form#addPercentage").submit(function() { var majorCodeInput = $('input[name="major_cd"]').val().trim(); var perc_Input = $('input[name="perc"]').val().trim(); if (majorCodeInput && perc_Input) { // Create Ajax Call $.ajax({ type: 'POST', url: '{% url "create-percentages" %}', enctype: 'multipart/form-data', data: { 'major_cd' : majorCodeInput, 'perc' : perc_Input, }, dataType: 'json', success: function (data) { if (data.Perc) { appendToPerTable(data.Perc); // Funcion to append data } } }); } else { alert("All fields must have a valid value."); … -
Failed to deploy my django project on heroku
I was going to deploy my django project on heroku, but I meet the error, I really have no idea how to do, please help, thank you a lot for your checking and answer in advance! -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/build_696b7f56_/lonelyisland/settings.py", line 24, in <module> SECRET_KEY = os.environ['SECRET_KEY'] File "/app/.heroku/python/lib/python3.7/os.py", line 681, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you … -
Django get max date for each month in query
I have a simple model with the fields date(DateTimeField) and value(IntegerField). I would like the query this model for the value of the last day for each month (see example output) date value 2020-01-01 55 2020-01-02 12 2020-01-03 13 ... 2020-01-31 34 ... 2020-02-01 14 2020-02-02 54 2020-02-03 16 ... 2020-02-28 23 ... 2020-03-01 16 2020-03-02 23 2020-03-03 16 ... 2020-03-31 7 Desired output: date value 2020-01-31 34 2020-02-28 23 2020-03-31 7 So far, I've managed to to this (But it involves quering the database alot, so I'd prefer a less database intensive solution) dates = MyModel.objects.annotate( month=TruncMonth('date') ).distinct() for date in dates: end_value = MyModel.objects.filter(date__month=date['month'].month).latest('date') print(end_value) -
Caching a whole page in PWA
While caching whole page in PWA using service worker, as we know we need to provide the route of that particular page. Here i am caching the home page of my website. Thus i pass / to be cached and it works fine. Then in my service worker, i wrote some code to first search in cache when a request is made for an asset and if is not found go to the server. Here is the code; self.addEventListener('fetch', evt => { evt.respondWith( caches.match(evt.request).then(casheRes => { return casheRes || fetch(evt.request); }) ) }); Everything works fine and i am 100% sure that there is no problem in the code but the problem is with what it returns. As my code first checks the cache to return something,here the home page, but the home page is completely different when a user is logged in and logged out. Cache stores the logged out home page which is completely correct but when i login, i get redirected to the / route as per my code but it again shows the same home page as that is stored in the cache. How to solve such problem? -
Call a function on Friday of every week and also filter a model by date range of next week in Django
I have a django application wherein I should call a mailer function on Friday of every week. Also I should get the data of a model based on the dates from saturday to next friday. How can I do this using python's in built functions? if today is "Friday": mailer_function() def mailer_function(): model_data = Model.objects.filter( birthday__range=["tomorrow(i.e., Saturday's date)", "next friday's date"], anniversary__range=["tomorrow(i.e., Saturday's date)", "next friday's date"] ) Here I should get the model_data whose birthday or anniversary dates are in the next week. How can I get the values of dates? -
No value for parameter
I'm currently coding a function that goes like this. def build_protein(self, request, phrase): protein = [] i = 0 while i < len(phrase): codon = phrase[i: i + 3] amino = self.translate_amino(codon) if amino: protein.append(amino) else: print(f"The codon {codon} is not in self.mapper_1") i += 3 if len(phrase) % 3: messages.error(request, "DNA chain must be divisible by 3") return redirect('/') return protein To do the message.error, I've been following this tutorial https://docs.djangoproject.com/en/3.1/ref/contrib/messages/. It says that I have to put the request in order to make the code work. However, if I write the request parameter in the function, this error appears: No value for argument 'phrase' in method call. It looks like it's a pylint error no value for parameter. What this means, is that the phrase parameter isn't being detected somehow. How can I solve this error -
I just to fetch the updated status
Hey i have created a system where after payment it will show PAID. I have a button to proceed to payment but when the payment is successful the button will turn to hidden.Like when the status is paid the button will be hidden Here is my model.py class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.CharField( max_length=100, blank=True, null=True, default="Unpaid") payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True) Here is my Views.py : def get(self, request, id): user_orders = Order.objects.get(pk=id) args = {'user_orders': user_orders} return render(self.request, 'Home/invoice.html', args) def post(self, request, *args, **kwargs): customer = Customer.objects.get(id=request.session['customer']['id']) user_orders = Order.objects.get(pk=kwargs['id']) total = user_orders.total balance = request.session['customer']['coin'] if balance >= total: balance = balance - total customer.coin = balance customer.save() Order.objects.filter(pk=kwargs['id']).update( status='PAID' ) request.session['customer']['coin'] = balance request.session.save() return redirect('/orders') return HttpResponse("Insufficient Balance") -
Is there an alternative to Django crispy form for rendering Django form?
Since I started to develop Django apps one year ago, I've use Django crispy form for rendering my forms. For my new project, I want to change form rendering to look more like a 'desktop application'. This project will be a electronic data capture tool, with many forms with lots of fields. I have found this design on Codepen by Rijdzuan Sampoerna I found very elegant and professionnal. So I would like a form rendering closed to this design. I want to be able to have multiple fields in a same line (not only one column), with fields smaller,... Before defining all css by myself, I wonder if there is a django form rendering I could use as crispy? any suggestions? -
DRF wrong throttling trigger
I have a APIView where I have set throttling for staff users. I have added view name in the scope as well. Here is the code snippet: permissions.py class IsStaffUser(BasePermission): def has_permission(self, request, view): return request.user and request.user.is_authenticated and request.user.is_staff views.py from rest_framework.views import APIView from myprj.somewhere.permissions import IsStaffUser from myprj.somewhere.throttling import MyThrottleRate class BaseView(APIView): permission_classes = (IsStaffUser,) class MyView(BaseView): throttle_classes = (MyThrottleRate,) def get(self, request, pk): # some stuff throttling.py from rest_framework.throttling import UserRateThrottle class BaseThrottling(UserRateThrottle): cache_format = 'throttle_%(scope)s_%(ident)s_(view_name)s' def get_rate(self): """ Determine the string representation of the allowed request rate. """ try: return self.THROTTLE_RATES[self.scope] except KeyError: msg = "No default throttle rate set for '%s' scope" % self.scope raise ImproperlyConfigured(msg) def get_cache_key(self, request, view): if request.user.is_authenticated: ident = request.user.pk view_name = view.request.resolver_match.func.__name__ cache_format = self.cache_format % { 'scope': self.scope, 'ident': ident, 'view_name': view_name } return cache_format else: raise APIException('You are not authorised') class MyThrottleRate(BaseThrottling): THROTTLE_RATES = { 'user': '20/hour', } I have set the rate to be 20/hour, but I am getting status code 429 on the first request of the day itself. I looked for the solution but couldn't find solution. Please help me to locate the error. Note: We are using apache with mod_wsgi -
Combining radio-button with a dropdown form
How can I combine radio-button inside a dropdown select form. I'll be grateful for your help. My codes: index.html <div class="card-header"> <div class="container"> <div class="row"> <form class="col-md-4"> <select class="form-control select2" > <option>Select Major Head</option> {% for major in majors %} <option>{{ major.pk }}: {{ major.description }}</option> {% endfor %} </select> <button type="button">Display!</button> </form> </div> </div> </div> -
how do i run this filter in Django?
i want to write a filter that gets the days with highest order or purchase and get the result as Monday , Tuesday, Saturday etc. -
How to get a request in post_save function
Hello I am using Post_save signal for sending a notification from the model .... But I am getting an error like this "sending_notification() missing 1 required positional argument: 'request' " @receiver(post_save, sender=Plan) def sending_notification(request, sender, instance,created, **kwargs): if created: notify.send(request.user, recipient = request.user, verb = "Some messages") -
Djangos m2m_changed trigger doesn't trigger properly
I have a model that looks as follows and I wish to trigger a method every time the user_ids field get's changed. Using the post_save signal obviously didn't do anything, as ManyToMany relationships are special in that way. class Lease(models.Model): unit = models.ForeignKey(Unit, on_delete=models.CASCADE) user_ids = models.ManyToManyField('user.User') Using the m2m_changed trigger as follows also didn't do anything, which got me puzzled. I don't really understand what is wrong with this code also having tried to leave the '.user_ids' out. There are no errors or anything, it just doesn't trigger when the user_ids from the Lease model are changed. @receiver(m2m_changed, sender=Lease.user_ids) def update_user_unit(sender, instance, **kwargs): print('Test') -
Is there a way to add custom fields in Django Rest Framework
I am creating a rest API for my Django-blog project and I have models Post and Post like models as you below Create your models here. class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) text = models.TextField() approved = models.BooleanField(default=False) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField( default=timezone.now, blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.text[0:100] class PostLike(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) And I have a post serialiser like class PostSerializers(ModelSerializer): likes_count = serializers.IntegerField(read_only=True) class Meta: model= Post fields = ['id','text','author', 'approved','created_date', 'likes_count' ] I wish the likes_count to be count for the PostLike objects with the post of the queried post. What is the right way to implement it? -
django signals pre_save when file is uploaded
Can I test in pre_save or post_save, if a file was uploaded / changed? Example: class Item(models.Model): name_123 = models.CharField(max_length=255) photo = models.ImageField() @receiver(pre_save, sender=Item) def my_callback(sender, instance, *args, **kwargs): if NEW photo was uploaded: resize it; I dont want to resize the image, if only the name_123 changed, but I want to resize it when a new Item was created and when the image changed (even when the same image with the same file name was uploaded. If I would use a front end CreateView or something similar, I could have check if the form_data contains file data but I want to use it in general (django admin too). Thanks