Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Only getting the below in the admin page only
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ food/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
jQuery closing a modal when a try to click anywhere
jQuery is showing unpredictable behavior, the following code displays a custom modal with a form inside but if I try to click anywhere, including the form inputs it calls the jQuery function and closes it. What may I be doing wrong? let fecharModal = $('#fecharModal'); let conteudoModal = $('#conteudoModal'); let modal = $('#modal'); let fora = $('#fora'); $(modal).on('click', [fecharModal, fora], function () { $(modal).hide(); $(conteudoModal).html(""); return false; }); <div id="modal" class="fixed z-10 inset-0 overflow-y-auto hidden"> <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"> <div id="fora" class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true"></div> <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span> <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full"> <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4"> <div class="sm:flex sm:items-start"> <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left" id="conteudoModal"> </div> </div> </div> </div> </div> </div> -
Django How can I order_by queryset with condition
class Order(models.Model): ..... payment_no = models.CharField(max_length=32, blank=True) ..... my model has field payment_no to store string that have 2 syntax prefix string + '-' + 8 digit number only 8 digit number for example 'stk-00000001', 'fad-00000002', '00000003'. I wanna know how to order only the 8 digit number. please guide me how to order it -
Django Aggregate on related set
I have following models in Django REST: class Transaction(models.Model): ... account = models.ForeignKey('transactions.Account', on_delete=models.CASCADE) charged_amount = MoneyField(max_digits=14, decimal_places=2, default_currency=None) datetime = models.DateTimeField() ... class Account(models.Model): name = models.CharField(max_length=255) ... I successfully received an expected aggregated list of periods by this query: GROUP_CASTING_MAP = { 'day': Cast(TruncDate('datetime'), output_field=DateTimeField()), 'month': Cast(TruncMonth('datetime'), output_field=DateTimeField()), 'week': Cast(TruncWeek('datetime'), output_field=DateTimeField()), 'year': Cast(TruncYear('datetime'), output_field=DateTimeField()), } GROUP_ANNOTATIONS_MAP = { 'day': { 'day': TruncDay('datetime'), 'month': TruncMonth('datetime'), 'year': TruncYear('datetime'), }, 'week': { 'week': TruncWeek('datetime') }, 'month': { 'month': TruncMonth('datetime'), 'year': TruncYear('datetime'), }, 'year': { 'year': TruncYear('datetime'), }, } group_by_field = 'month' periods = Transaction.objects \ .annotate(**self.GROUP_ANNOTATIONS_MAP[group_by_field]) \ .values(*self.GROUP_ANNOTATIONS_MAP[group_by_field]) \ .annotate(total_amount=Sum('charged_amount'), period=self.GROUP_CASTING_MAP[group_by_field]) \ .values('total_amount', 'period') But I am looking for a way to get a list of accounts with aggregated periods: [ { "id": 1, "name": "accountName", "periods": [ { "period": "2021-05-01T00:00:00+00:00" "total_amount": 152 }, { "period": "2021-06-01T00:00:00+00:00" "total_amount": 1333 } ] } ] How to connect annotated transactions to Account queryset? Thanks -
ModuleNotFoundError: No module named 'application' error in AWS
I am trying to deploy a django's app to aws. I am getting the error " ModuleNotFoundError: No module named 'application'" when I try to create the app (django create django-env). I don't know why. My django.config file is: option_settings: "aws:elasticbeanstalk:projectlication:environment": DJANGO_SETTINGS_MODULE: project.settings "aws:elasticbeanstalk:container:python": WSGIPath: project.wsgi:application My application name is project, so I don't know what is wrong. Thank you -
'CountryPDF' object has no attribute 'data'
Please help!What I am doing wrong? I have views.py to generate PDF. It is generate PDF success if context: 'Sometext'.It open me PDF link. But When I take django models.It output me : 'CountryPDF' object has no attribute 'data' my views.py class CountryPDF(core.PDFView): template_name = 'application_pdf.html' def get_context_data(self, **kwargs): return {'data': self.data} def get_file_name(self, context): return 'test1.pdf' So HTML file: application_pdf.html {% for item in data %} <td>{{ item.name }}</td> <td>{{ item.address }}</td> {% endfor %} url: path('cabinet/<int:pk>/download-pdf/', views.CountryPDF.as_view(), name='country-download_pdf'), What is the problem with context data? What I am doing wrong? -
Is possible get value by name of column in Pandas-Python without order?
I have a csv make in Python where I have different names of columns: response['Content-Disposition'] = 'attachment; filename="upload.csv"' writer = csv.writer(response) writer.writerow(['whatever1','whatever2','whatever3','whatever4','whatever5']) I am trying to get the values of these columns by name, but I can only by the order that I have configured. data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) cols = ['whatever1','whatever2','whatever3','whatever4','whatever5'] df = pd.read_csv(io_string, names=cols) I mean, If I change the order of the columns in excel, it not respect the name of the column, it take the value of the column in order. For example, in excel, if I change the order, Pandas take the column with name whatever2, like whatever1. whatever2 whatever1 1 0 1 0 2 14 3 20 So, Can I take the values of the column by the name of the column, regardless of the order? Thanks. -
Please how can get the number of listings in a category, i have tried
here is my complete model class Category(models.Model): name = models.CharField(max_length=500) icon = models.ImageField(upload_to='photos/icons/%Y/%m/%d/') def __str__ (self): return self.name class Listing(models.Model): name = models.CharField(max_length=300) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=False, null=True) email = models.EmailField(max_length=300) description = RichTextField(blank=False, null=False) photo_main = models.ImageField(upload_to = 'photos/%Y/%m/%d/') photo_1 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True) photo_2 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True) photo_3 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True) photo_4 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True) location = models.CharField(max_length=500, null=True) phone_number = models.CharField(max_length=11, default = "#") website = models.CharField(max_length=150, blank=True, default="#") facebook = models.CharField(max_length=150, blank=True, default="#") instagram = models.CharField(max_length=150, blank=True, default="#") opening_time = models.CharField(max_length=7) closing_time = models.CharField(max_length=7) is_published = models.BooleanField(default=False) posted_date = models.DateTimeField(auto_now_add=True) user_id = models.IntegerField(blank=True) def __str__ (self): return self.name here is my views from django.shortcuts import render from listings.models import Listing from listings.models import Category from testimonies.models import Testimony from our_team.models import Team_Mate from testimonies.models import Testimony from django.db.models import Count def index(request): the part is working perfectly. listings = Listing.objects.order_by('-posted_date').filter(is_published=True)[:6] category = request.GET.get('category') categories = Category.objects.all()[:7] counting listings in a category count_cate = Category.objects.all() cate_count = count_cate.count() if category == None: listings = Listing.objects.order_by('-posted_date').filter(is_published=True)[:6] else: listings = Listing.objects.filter(Category__name=category) here is my context context ={ 'listings': listings, 'categories': categories, 'cate_count': cate_count, } return render(request, 'pages/index.html', … -
Replacing Django's Primary Relational Database with a NOSQL database
I am building a Django application that is similar to a social media website. I am using firebase's library **Pyrebase** for Auth and storing various user-based data into it. But there are some tables, for example. **django.sessions** which I am not able to replace and migrate totally to Firebase. Under the ```settings.py```, I am unable to understand what needs to be changed, so that the inbuilt tables that are created after performing ```python manage.py migrate``` would create objects in the firebase rather than in SQL. I surely can use firebase tokens as sessions id's but is this the authentic way to perform such actions as that way I am making no changes to the Middlewares present in the Django settings? I am aware that Django uses ORM but is there any way to completely change the Django primary databaseCan a Django app could run completely without using SQL for any type of data storage? -
How to make "next" and "back" in Django forms?
I have a form by which I add hotels to the site (as on Booking.com). In order to complete the form of adding a hotel, I need the form to be two or more pages, where everything will be filled in in more detail. I wonder how I can do this? Should I use AJAX? For example, I will use my model, form and function. Also, when I go "back" I should be able to edit my form. models.py from django.db import models from account.models import Account class Hotel(models.Model): customer = models.ForeignKey(Account, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) short_description = models.TextField(max_length=250) long_description = models.TextField(max_length=2000, null=True) HOTEL_STAR = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5') ) star = models.TextField(max_length=1, default=5, choices=HOTEL_STAR, null=True) picture = models.ImageField(upload_to='images/%Y/%m/%d/',default="images/default.jpg" , blank=True) created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.name) forms.py from django.forms import ModelForm from .models import Hotel class HotelForm(ModelForm): class Meta: model = Hotel exclude = ('customer',) views.py @login_required def add_hotel(request): form = HotelForm() if request.method == "POST": form = HotelForm(request.POST, request.FILES) if form.is_valid(): data = form.save(commit=False) data.customer = request.user data.save() return redirect('/') context = {'form':form,} return render(request, 'add_hotel.html', context) html {% extends 'base.html' %} {% load static %} {% block … -
How to refresh the JWT token in nuxt.js?
I want to use JWT authentication in my nuxtjs app but it's not refreshing the token. For testing purposes, I set the access token expire time 5 seconds and refresh token for 30 minutes. Access token expire after 5 seconds but the token is not refreshing after 5 second its logged-out I'm using the Django rest framework and in nuxt I'm using nuxt auth v5 settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), 'ACCESS_TOKEN_LIFETIME': timedelta(seconds=5), 'REFRESH_TOKEN_LIFETIME': timedelta(minutes=30), } nuxt.config.js auth: { localStorage: false, strategies: { local: { scheme: 'refresh', token: { property: 'access', type: 'JWT', required: true }, refreshToken: { property: 'refresh', }, user: { property: false, autoFetch: true }, endpoints: { login: { url: '/jwt/create/', method: 'post',}, refresh: { url: '/jwt/refresh/', method: 'post',}, user: {url: '/users/me/', method: 'get' }, logout: false }, } } } } I'm little new in JWT and nuxt. Correct me if I'm wrong. My main goal is just to refresh the token automatically when access toke is expired. -
Slack API how to get conversations.list for different workspaces that installed the app?
Using this app as an example, how could I call conversations_list method while differentiating the conversations list I want for different workspaces? Do I have to construct a different WebClient with some specific token? If so, how do I store OAuth tokens generated for each workspace (as in I don't think the code example linked above handles storing OAuth tokens)? Thanks so much in advance! -
How to capture dynamic URL part to return a list in Django
I need to code an API which will be used by dropdowns in a react form. There are multiple dropdowns and exposed API url also follow similar pattern. For example - /api/trend/foo?bar=0 /api/trend/foo?bar=1 /api/trend/baz?bar=0 /api/trend/baz?bar=0 /api/trend/fish?foss=1 /api/trend/baz?foss=2 So it boils down to /api/trend/{table}?{filter}={val} which will return a list {col}, which further boils down to SELECT col FROM table WHERE filter=val I don't want to write multiple functions for same pattern. I am looking for something like this # in views.py def dropdown_api(request, table, filter): # fire the SQL statement # get the result in a df/list # serialize the result # return the response to consume by react # in urls.py path('api/trend/{table}?{filter}={val}', views.dropdown_api) #something like this to capture the dynamic url content -
how to add images int database in django with out showing the path of images in choosen button
class ProductForms(forms.ModelForm): images1 = forms.ImageField(widget=forms.FileInput,) class Meta: model = Product fields = 'all' -
Error after user creation using Django allauth
After setting up Django-allauth using Microsoft sql as the backend database i get the following error after registering a new user. However user is created and can log in as long as account_email_verification is set to optional django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]An expression of non-boolean type specified in a context where a condition is expected, near ')'. (4145) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") also get the same error when trying to verify email address through emailed link any help is appreciated thanks -
TypeError at /show_cart/ can only concatenate str (not "int") to str
I am building an e-commerce site and i'm working on a quantity & price section. What I want to do is, when the user increses the quantity of the product the price should also change depending upon the quantity. This is views.py def show_cart(request): if request.user.is_authenticated: user = request.user cart = Cart.objects.filter(user=user) amount = 0 shipping_amount = 70 total_amount = 0 cart_product = [p for p in Cart.objects.all() if p.user == user] if cart_product: for p in cart_product: temp_amount = (p.quantity * p.product.discounted_price) amount = temp_amount + amount total_amount = amount + shipping_amount return render(request, 'app/addtocart.html', {'carts':cart, 'amount':amount, 'total_amount':total_amount}) this is models.py: Here is have added comma sepeated integers. coz i wanted the products price to look like this: 14,999 insted of 14999 this. class Product(models.Model): title = models.CharField(max_length = 100) selling_price = models.CharField(validators=[validate_comma_separated_integer_list],max_length=200, blank=True, null=True,default='') discounted_price = models.CharField(validators=[validate_comma_separated_integer_list],max_length=200, blank=True, null=True,default='') I know i am getting this error coz coma seperated interger is considered as a String & quantity is an integer field. So, i want to know that how can i solve this problem, when the user increases the quantity of the product the price should also change depending upon the quantity. -
Why do I get CommandError: App 'appname' does not have migrations in heroku?
So I'm trying to deploy my Django project with heroku. I have successfully deployed the project, but then ran into this issue while trying to migrate. Below is my settings.py ... import dj_database_url DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_project_db', 'USER': 'ryan', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', } } db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) I have run python manage.py makemigrations appname and python manage.py migrate appname in local. Then I ran heroku run python manage.py makemigrations appname, which worked without any error. Below is what I got. Migrations for 'appname': appname/migrations/0001_initial.py - Create model Book - Create model Category - Create model Content Seeing it worked fine, I ran heroku run python manage.py migrate appname. But then I got this issue : CommandError: App 'appname' does not have migrations. What do you think is the problem? Thanks in advance. FYI, when I try to access the model in the admin page, I see an error page saying the relation does not exist. -
How to serialize creation with Django Rest Framework models with many-to-many field and foreign-key, when models data inside some field in request?
I am trying to serialize this JSON { "api_key": "<something key>", "contract_id": 3808, "params": { "contract_id": 3808, "title": "Глюкоза", "doctor_description": "Запрашивает у пациента уровень глюкозы в крови.", "patient_description": "Пожалуйста, измерьте уровень сахара в крови до еды с помощью глюкометра и укажите его в поле ниже.", "thanks_text": null, "fields": [ { "category": "glukose", "description": "ммоль/л", "max": null, "min": null, "text": "Глюкоза", "type": "float", "uid": "24c2258b-d338-4184-a114-5cae3721bb16" }, { "category": "information", "text": "Комментарий", "type": "textarea", "uid": "93722301-d652-4903-8404-e56da4d31ad7" } ] } } Inside params there is instance of model MeasurementTask (models.py): class MeasurementTask(models.Model): title = models.CharField(max_length=255) doctor_description = models.TextField() patient_description = models.TextField() thanks_text = models.TextField(null=True) contract_id = models.ForeignKey(Contract, on_delete=models.CASCADE) fields = models.ManyToManyField(MeasurementTaskGeneric) is_sent = models.BooleanField(default=False) is_done = models.BooleanField(default=False) It related by ManyToManyField with MeasurementTaskGeneric: class MeasurementTaskGeneric(models.Model): uid = models.CharField(max_length=255, unique=True) category = models.CharField(max_length=255) description = models.CharField(max_length=255, null=True) max_value = models.FloatField(null=True) min_value = models.FloatField(null=True) text = models.CharField(max_length=255) value_type = models.CharField(max_length=255) And with foreign key with Contract: class Contract(models.Model): contract_id = models.IntegerField(unique=True, primary_key=True) speaker_active = models.BooleanField(default=False) def __str__(self): return "Contract id - {}".format(self.contract_id) With request I need to create instance of MeasurementTask and create (or get if it already exists) instance of MeasurementTaskGeneric, get instance of Contract by Contract.contract_id and add it ti foreignKey to MeasurementTask.contract_id … -
Mongo db gets truncated frequently
Django version 3.0.5 mongo version 4.4.6 settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'ENFORCE_SCHEMA': True, 'NAME': 'cpv', 'HOST': 'xx.xx.xx.xxx', 'PORT': 27017, 'USER': 'username', 'PASSWORD': 'password', 'MONGO_AUTH_SOURCE': "admin" } } When I enable authorization in mongod.conf security: authorization: "enabled" And try to migrate I am getting below error pymongo.errors.OperationFailure: command listCollections requires authentication, full error: {'ok': 0.0, 'errmsg': 'command listCollections requires authentication', 'code': 13, 'codeName': 'Unauthorized'} -
Django imagefield don't shows on template
i've a model with an imageField and when i upload file works and in database adds file path to img field but when i try call it in my template seem is always empity item.img instead other fields works well, to show it i use a listview model def content_file_name(instance, filename): ext = filename.split('.')[-1] # filename = "%s_%s.%s" % (instance, instance.questid.id, ext) return f"uploads/items/{instance.id}.{ext}" class Item(models.Model): type = models.IntegerField(choices=TYPE, blank=False, default=NO_CAT) name = models.CharField(max_length=250 ) description = models.CharField(max_length=250, blank=True ) img = models.ImageField(upload_to=content_file_name, blank=True) tags = models.ManyToManyField(Tag, through='Item_Tags') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) active = models.BooleanField(default=False) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) def __str__(self): #metodo righiesto return self.name my template <div class="card-columns"> {% for item in page_obj %} <div class="card"> {% if item.img %} <img class="card-img-top" src="{{item.image.url}}" alt="Card image cap"> {% else %} NO image {% endif %} <div class="card-body"> <h5 class="card-title">{{item.name}}</h5> <p class="card-text">{{item.description}}</p> <p class="card-text"><small class="text-muted"></small></p> </div> </div> {% endfor %} </div> -
count hours of a week depending on a given date django
I have a model that has 2 fields: a date as a Datefield and hours as a Decimalfield, and a form in which the user input a date. I want to count the hours in the week based on the input date. -
How do I display subcategories in the Django admin based on the selected category?
i am new at django, and i am doing online store, and i want to create items by using admin panel. When i choose main category for item and tried to choose sub i see nothing. I tried ChainedForeignKey my model from django.db import models from smart_selects.db_fields import ChainedForeignKey class Collection(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) category = ChainedForeignKey(Category, chained_field='category', chained_model_field='collection') description = models.TextField(blank=True) size = models.CharField(max_length=255) price = models.PositiveIntegerField() image = models.ImageField(upload_to='photos/%Y/%m/%d/') def __str__(self): return self.name -
how to subtract from DateTimeField to DateField in Django
.annotate(gap=ExpressionWrapper(F('create_date') - F('register_date'), output_field=DurationField() As the title suggests, is it impossible to operate on two fields DateField and DateTimeField in Django? When I google and calculate when the db models type is different, I said that expressionwrapper can be used. When I wrote the code and ran it, 'gap': datetime.timedelta(0) is output. For reference, create_date is the date created when data is added and is in datetime format. register_date is a date format of yyyy-mm-dd format entered by selecting a date from the calendar. Is there any way to count both fields? -
General delete view in django gives error after slugify urls
I am getting error on delete view Generic detail view ItemDeleteView must be called with either an object pk or a slug in the URLconf. URL: path('item/<slug:item_slug>/remove', ItemDeleteView.as_view(), name='item_delete'), VIEW: class ItemDeleteView(DeleteView): model = Item template_name = 'waqart/item_delete.html' success_url = reverse_lazy TEMPLATE: <a class='text-blue-500 text-xs' href="{% url 'item_delete' item.slug%}">Delete this Post</a> -
Schedule a job to run after 30 seconds using Django-rq
I'm trying to implement the django-rq since I have some scraping that sometimes fails and has to be scheduled to run again after, say, 30 seconds. As far as I understand, I push a job the queue by django_rq.enqueue(scrape_func, foo, bar=baz) is there a way to push it to the queue and give it A timestamp to run (like Airflow) e.g 0 01 * * * or a time-delay before run (e.g 30 sec)