Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to decrease the days remaining when the days are passed
Thank you in advance, I am new to Django rest I am creating a JobsPortal website with Django rest but the problem is when the days pass the days remaining is still the same. How to decrease the days remaining when the days are passed. And also how to delete the data automatically after the before date is passed. My model class Jobs(models.Model): post_date=models.DateField( default=_datetime.date.today, blank=False,editable=False) before_date=models.DateField(blank=False,) days_left=models.IntegerField(null=True, blank=True) def save(self,*args, **kwargs): self.days_left=((self.before_date - self.post_date).days) if self.days_left>=0: super(Jobs, self).save(*args, **kwargs) else: return False -
Duplicated django ORM query n+1
I have a models looks like this class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) income_period_choices = (("Weekly", "Weekly"), ("Fortnightly", "Fortnightly")) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) class FamilyGroup(models.Model): name = models.CharField(max_length=10, choices=name_choices) transaction = models.ForeignKey( Transaction, on_delete=models.CASCADE, related_name="family_groups" ) family_type = models.ForeignKey( FamilySituation, on_delete=models.PROTECT, null=True, blank=True ) last_rent = models.DecimalField( help_text="per week", max_digits=7, decimal_places=2, null=True, blank=True ) @property def rent_assessment_rate(self): return RentAssessmentRate.objects.get(active="Yes") # here i think i should add select_related maybe or something, but im not sure @property def ftb_rate(self): return self.rent_assessment_rate.ftb @property def cra_rate(self): return self.rent_assessment_rate.cra @property def maintenance_rate(self): return self.rent_assessment_rate.maintenance views def index(request): transaction = Transaction.objects.all().prefetch_related('family_groups') return render(request, 'cra/index.html', {"transaction":transaction}) So I'm getting a duplicated queries from RentAssessmentRate table while trying to retrieve the data on the FamilyGroup table. What would be a good approach to avoid such duplicates? Thanks in advance -
problem with django python web app and postgres psycopg2?
i need urgent help. i had problems with postgres and installed psycopg2 and binary aswell. it says it is installed. but it shows this error. enter image description here[enter image description here][2] Import "psycopg2" could not be resolved Import "psycopg2.extensions" could not be resolved Import "psycopg2.extras" could not be resolved -
Webpack for Django Project on Docker (Production)
I have a Django project, and I've successfully installed and run Webback with the purpose of minifying frontend files (CSS, JS, HTML) using npm (and creating config.js) - I want to make Docker do this job automatically from the production server side. I tried to do it from the backend through Django settings (STATIC_FILE), but failed. var config = { module: {}, }; var src = '/xx/xx/xx/xx/xx/xx/'; var File1JS = Object.assign({}, config, { entry: src + 'static/assets/js/file1.js', /// Source File output:{ filename:'file1.js', path: src + 'static/assets/js' /// Ourput File (Minified File) } }); var File2JS = Object.assign({}, config,{ entry: src + 'static/assets/js/file2.js', output:{ filename:'file2.js', path: src + 'static/assets/js' } }); module.exports = { File1JS, File2JS }; Any advice or help? -
How can I list all objects associated to a particular object via foreign key in Django?
I have a ListView that lists all Vehicle objects. How can I make another view, that would show a list of all Job objects associated with that vehicle when I click on the link marked ### next to that vehicle? models.py class Vehicle(models.Model): vehicle_reg = models.CharField(primary_key=True, max_length=7) vehicle_make = models.CharField(max_length=15) vehicle_model = models.CharField(max_length=15) class Job(models.Model): car = models.ForeignKey(Vehicle, on_delete=models.CASCADE) html <table class="table"> <thead class="thead-dark"> <tr class="table-light"> <th scope="col">Registration</th> <th scope="col">Make</th> <th scope="col">Model</th> </tr> </thead> <tbody> {% for vehicle in vehicleList %} <tr class="table-light"> <td class="lead"> <a href="{% url '###' pk=vehicle.pk %}">{{vehicle.vehicle_reg}}</a></td> <td class="lead">{{vehicle.vehicle_make}}</td> <td class="lead">{{vehicle.vehicle_model}}</td> </tr> views.py class VehicleListView(ListView): context_object_name = 'vehicleList' model = Vehicle template_name = 'vehicles/vehicle_list.html' Thank you in advance. -
How to change design of filters in django-filter
I have such filters: 'Отправить' means send data. This is my filter: class BookFilter(django_filters.FilterSet): price = django_filters.RangeFilter(label='Price between') class Meta: model = Book fields = ['title', 'price', 'genre', 'language'] This is how i display my filters: <form method="get"> {{ filter.form.as_p }} <input type="submit" /> </form> So, i have two questions: How can i change design of these filters?(for example to delete '-' in 'Price between') Is there any way to display these filters by a for loop that i could to wrap it in a div container or set a class attribute(idk what is more comfortable)? P.S. I don't use Django Rest Framework -
Profile is not getting created for the new user after extension of the user model
Before extending the user module, I was easily able to register new users and the page would get redirected to the login page. Now on registering new users, the profile is not getting created and the page is also not getting redirected. The new user does get created though and sometimes the error is object does not exist, user profile does not exist, and sometimes the error is forbidden, csrf verification failed. I dont know where I'm going wrong. existing users are able to login and update profiles but new users I'm having a problem with. Models.py is: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User,null= True ,on_delete= models.CASCADE) profile_pic = models.ImageField(null = True, blank= True) first = models.CharField(max_length=500, null=True) last = models.CharField(max_length=500, null=True) email = models.CharField(max_length=500, null=True) mobile_number = models.IntegerField(null=True) location = models.CharField(max_length= 500, null= True) postal = models.IntegerField(null=True) def __str__(self): return self.first My forms.py is: from django.forms import ModelForm, fields from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User from .models import * class CreateUserForm(UserCreationForm): email = forms.EmailField() password2 = None class Meta: model = User fields = ['username','first_name', 'last_name','email', 'password1'] class ProfileForm(ModelForm): class Meta: model = Profile fields = … -
Django: Changing response URL/PATH
How could I change the response URL from a view(CBV in my case)? for example: I am typing: /some_path/ redirecting(in middleware) to: /another_path/ responsing Now I have '/another_path/' in the browser's address bar, but need '/some_path/'. -
Getting distance between zipcode (pyzipcode)
Using pyzipcode (django python package), I'm able to get the zip codes within a radius of another zipcode (local_zip) using the code below. in_radius = [z.zip for z in zcdb.get_zipcodes_around_radius(local_zip, 10)] objects_output = Model.objects.filter(Q(zipcode__in=10)).distinct() I am able to find all the zipcode in let's say 10 miles of a chosen zipcode (local_zip), but I want the know the exact mileage difference. This would be the desired output: zipcode, miles 90101, 8 90210, 3 90211, 4 ... ,... 90234, 10 -
Выстраивание полей в нужно порядке
Есть вывод полей: { "id": 1, "text": "Тестовый текст1" "order": "1" }, { "id": 2, "text": "Тестовый текст2" "order": "2" }, { "id": 3, "text": "Тестовый текст3" "order": "3" } Как поменять местами поля в соответствии с тем как захочет пользователь. Тоесть скорее всего нужно поменять строки в самом БД. Как это можно реализовать с помощью REST API? { "id": 1, "text": "Тестовый текст1" "order": "1" }, { "id": 2, "text": "Тестовый текст3" "order": "3" }, { "id": 3, "text": "Тестовый текст2" "order": "2" } -
How to insert data on mongo DB
i'm learning how to code, and i'm currently on Flask, django, MongoDB framework. I'm trying to create a new user and adding it to my mongodb. when i "send it" on postman i get this error: DeprecationWarning: insert is deprecated. Use insert_one or insert_many instead. id = mongo.db.users.insert( I've already tried using the suggestions on the error message above but still ain't working Here's my code: def create_user(): #recieving data username = request.json['username'] password = request.json['password'] email = request.json['email'] if username and email and password: hashed_password = generate_password_hash(password) id = mongo.db.users.insert( {'username': username, 'email': email, 'password': hashed_password} ) response = { 'id': str(id), 'username': username, 'password': password, 'email': email } return response i'm sure it's just me being totally noob on the subject, but i couldn't find the solution. Thanks! -
views.my_login_view didn't return an HttpResponse object. It returned None instead
The view accounts.views.my_login_view didn't return an HttpResponse object. It returned None instead. here is the code def my_login_view(request): form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('/Skolar/') else: return HttpResponse('<h1>Page was found</h1>') else: return render(request, "login.html", {'form': form}) -
Webpack for Django Project on Docker (Production)
I have a Django project, and I've successfully installed and run Webback with the purpose of minifying frontend files (CSS, JS, HTML) using npm (and creating config.js) - I want to make Docker do this job automatically from the production server side. I tried to do it from the backend through Django settings (STATIC_FILE), but failed. Any advice or help? -
How to put my docker container on a production server?
(I'm new with Docker and Django) It's seem to me that what i'm tring to do is the basics, but i'm struggling. I want to setup my production environment with docker on an Ubuntu server. I'm using django & django REST framework & mysql database to build my application. I already have my 2 images : one for django one for MySQL I also have my container on my computer which i can run it with : docker-compose up How to put my docker container on a production server ? (It's maybe not this way i should do, i lets you guide me ;) ) -
Page not found (404)(No category matches the given query.)
I am trying to activate the navigation bar links using context_processors.py file .Here I used a dropdown menu and some links to load contents in the same html page.Dropdown menu is for selecting the 'category' and links are used for selecting the 'genre'.'category' app is used for adding the categories via admin panel and 'genre' app is used for adding the genres.'review' app is created for display the details.In 'review' app model 'details' is created and 'category' model in the 'category' app and 'genre' model in the 'genre' app is defined in the 'details' model using ForeignKey.I want to display items in the same page(index.html) when clicks a link.Link given in dropdown menu worked properly,but when I click links other than links mentioned in dropdown menu are not working and it display's 404 error like below: Page not found (404) No category matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/drama/ Raised by: review.views.index Using the URLconf defined in movie.urls, Django tried these URL patterns, in this order: admin/ [name='index'] <slug:category_slug>/ [name='index_by_category'] The current path, drama/, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, … -
Upload File to S3 with FileSystemStorage
I have set up a function that gets a file from an AJAX request and I want to upload that file to an S3 bucket. The function currently works and can save files to my local storage, but it doesn't seem to work with S3. from django.core.files.storage import FileSystemStorage from django.http import JsonResponse def upload_video(request): if request.method == 'POST': new_file = request.FILES['video'] fs = FileSystemStorage() filename = fs.save(new_file.name, new_file) uploaded_url = fs.url(filename) return JsonResponse({'video_url' : uploaded_url}) -
Django Authentication Form Customization
I am trying to customize Django's login form and the solution I have come up with before is as follows: class MyAuthenticationForm(AuthenticationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget = forms.widgets.TextInput(attrs={ 'class': 'form-control' }) self.fields['password'].widget = forms.widgets.PasswordInput(attrs={ 'class': 'form-control' }) and of course in my app I have the path as: path('accounts/login', LoginView.as_view(authentication_form=MyAuthenticationForm), name='login'), This has worked in the past for me but for some reason on this particular project it is not injecting the class into the input and I genuinely have no idea why. Does anyone have any suggestions on what may be the issue? I feel like I am going crazy trying to solve this seemingly easy issue haha. I feel like maybe I am overlooking something simple but I cannot see it. -
How to enforce uniqueness on many-to-many relationship with object attribute in Django?
Suppose I have the following models: class Item(db.Model): containers = db.ManyToManyField(Container) name = db.CharField(max_length=100) class Container(db.Model): name = db.CharField(max_length=100) I believe there is an automatic constraint that Item and Container can be associated no more than once. From Django docs on through: If you don’t want multiple associations between the same instances, add a UniqueConstraint including the from and to fields. Django’s automatically generated many-to-many tables include such a constraint. However, I also want a constraint that no two items with the same name can be in the same container. How do I enforce that? Maybe it's not possible at the model level? -
Django-SHOP deferred ForeignKeys
this problem is driving me crazy because I simply cannot wrap my head around it: I am working with Django-SHOP and I need to add ForeignKeys to Django-Filer because my custom customer model, my Videomodel/Articlemodel which both derive from Product(Baseproduct) need a ForeignKey to Django-Filer. These to pages from the Docs really do not help me: https://django-shop.readthedocs.io/en/latest/reference/deferred-models.html https://django-shop.readthedocs.io/en/latest/reference/product-models.html and I do not understand why e.g. in a mapping table you reference Baseproduct (second link, 4.3) or why - if I create a mapping table for Video.videofile - the error occurs that Video.videofile has not been mapped. If anyone could explain that I cannot even tell what exactly is bothering me about this I simply cannot seem to grasp the whole point of this. thanks in advance! -
TypeError: __call__() missing 1 required positional argument: 'send' Django
When I run the project through the gunicorn (command: gunicorn --bind :8000 myproject.asgi:application), I get this error. Error Traceback (most recent call last): File "/venv/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 136, in handle self.handle_request(listener, req, client, addr) File "/venv/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 179, in handle_request respiter = self.wsgi(environ, resp.start_response) TypeError: __call__() missing 1 required positional argument: 'send' asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.base') django_asgi_app = get_asgi_application() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from chats import routing application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ) ), }) chats.routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/messages/(?P<username>[-:\w]+)/$', consumers.ChatConsumer.as_asgi()), ] -
Problem with static folder IIS for Django
I have a static folder set in django to a network path STATICFILES_DIRS = [ "//SERVER/Shared1/FOLDER_210121/", ] and I have 2 pages that have links to this static subfolders link1: http://server2:8044/static/folder1/COINS_LIVE_OU164/user1310200781810167.tif link2: http://server2:8044/static/folder2/COINS_LIVE_OU164/user2310200781810167.tif however link1 works perfectly but link 2 gives me an error as file not found but the file does exist, and from IIS I have set a virtual directory aliased as "static" with the root folder that contains the subfolder from where I get the files. I can navigate from the virtual directory to both files, the virutal directory was created with the defaultAppPool user. is there something else I could check? (if I run the manage.py runserver command and I use localhost I can download both files, the issue is when using it from the IIS). if I print the value of static in a label the path is ok, so I'm guessing permission, but where can I be missing the configuration? Thank you. -
Configuring Google Cloud App Engine w Django
I'm following this tutorial to deploy Django with Google Cloud. At the timestamp (13:39) he goes into settings.py in the Django project in VS Code and swaps some placeholders out for his own Google Cloud credentials. My settings.py however looks very different. The only thing in block caps that looks as if it might be a placeholder is "GOOGLE_CLOUD_PROJECT" and "SETTINGS_NAME". This is the part of the installation I can't get past because at the next step when I try to execute python manage.py makemigrations I get sent here: else: raise Exception("No local .env or GOOGLE_CLOUD_PROJECT detected. No secrets found.") Hoping someone can glance over my settings.py and identify what I'm missing why that if block is going to Exception. One thing to note: The top imports environ and google.cloud are not resolved. idk if that's got anything to do with it. This is how the file came out the can. I don't want to mess with it in case tshtf :D settings.py import io import os import environ from google.cloud import secretmanager # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # [START gaestd_py_django_secret_config] env = environ.Env(DEBUG=(bool, False)) env_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(env_file): # … -
Errors including the custom model method in Django admin
What I tried to do I tried to make custom admin method to include product thumbnail preview in my admin panel. product_thumbnail is a ImageField inside the Product Model which has general information of each products that I upload on the admin panel. I wanted to make product_thumbnail as not required. Therefore, I set null=True and blank=True in my models.py also. class Product(TimeStampModel): ... product_thumbnail = models.ImageField(verbose_name='상품사진', null=True, blank=True, upload_to='product_thumbnail') I created the custom function as below and included it in list_display admin option inside of ProductAdmin model. def thumbnail_preview(self, obj): return mark_safe(f'<img src="{obj.product_thumbnail.url}" width="40%" />') thumbnail_preview.short_description = '상품사진' Which error did I get? I got the error as below: ValueError: The 'product_thumbnail' attribute has no file associated with it. What I have tried to solve issue This might be because some Product may not have product_thumbnail so that Django admin failed to load its url due to its null value. I used try-except so that if Django fails to find product_thumbnail associated with that product, then it can throw error text. def thumbnail_preview(self, obj): try: return mark_safe(f'<img src="{obj.product_thumbnail.url}" width="40%" />') except obj.product_thumbnail is None: return HttpResponse('No images') thumbnail_preview.short_description = '상품사진' Then I got another error as below: TypeError: catching … -
Django raw sql query issue using class based view
def home(request): with connection.cursor() as cursor: os = '%(USN-%' sql = "select TITLE from XYZ where LANG='en' and TITLE like '%(USN-%'" cursor.execute(sql) row = cursor.fetchone() print(row) return HttpResponse("<h1>I am Home</h1>") This results correct output, however if I convert this into a class based view, class Home(APIView): def get(self, request): with connection.cursor() as cursor: sql = "select TITLE from XYZ where LANG='en' and TITLE like '%(USN-%'" cursor.execute(sql) row = cursor.fetchone() print(row) return JsonResponse(row[0], safe=False) django.db.utils.DatabaseError: ORA-00933: SQL command not properly ended Error occurs. I am using cx_Oracle package -
"TypeError: 'NoneType' object is not callable" error in a Class
I'm coding an online education course website in Django to learn about Django. @admin.site.register(Course) class CourseAdmin(admin.ModelAdmin): list_display = ('name', 'available',) # listede gösterim şekli list_filter = ('available',) # filtreleme search_fields = ('name', 'description',) # isim ve açıklamaya göre yapma```` I wrote this code block. But when I type $ python3 manage.py runserver on the terminal to run the code, and the program gives me a TypeError. Error message's full form is below; TypeError: 'NoneType' object is not callable I googled this error and most of the websites are saying me that this problem's reason is your written functions. But I didn't write even a function. I wrote just a class. Where is the problem? Can you help me