Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form Update with Queryset
I have a model with field ManyToMany, like code bellow : #MODEL class Car(models.Model): description = models.CharField(max_length=100, null=True) is_available = models.BooleanField(default=True, null=True, blank=True) class Rental(models.Model): invoice_number = models.CharField(max_length=100, null=True, blank=True) car = models.ManyToManyField(Car) And forms.py code : class RentalUpdateForm(forms.ModelForm): class Meta: model = Rental fields = ['car'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.fields['car'].queryset=Car.objects.filter(is_available=True).all() My question is; how to display car on RentalUpdateForm with current values selected also display another car with condition is_available=True ? -
How to show first 2-3 sentences of some content in django template?
I have a post object which has content attribute which is basically a TextField. I want to show first few sentences (not words, I want it to truncate after 2-3 full stops, or something like that) as preview of post on my webpage. {{ post.content }} How do I do that in my template? -
Is there a way to load static files without the tag "{% load static %}"?
I need to load the files in site without the first line tag load static -
MEDIA_ROOT vs MEDIA_URL (Django)
I read the documentation about MEDIA_ROOT and MEDIA_URL then I could understand them a little bit but not much. MEDIA_ROOT: Absolute filesystem path to the directory that will hold user-uploaded files. MEDIA_URL: URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be served in both development and production environments. I frequently see them as shown below: # "settings.py" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' So, what are "MEDIA_ROOT" and "MEDIA_URL" exactly? -
How can I 'trim' the unnecessary input fields from GenericView?
In my current project i am creating a little CMS so the client will be able to update his gallery on the website with new images and replace the old ones. For this I am using the generic Views to simplify the whole process. Adding a new image was no problem, but the UpdateView is providing some html elements, which I dont want my client to see: Here is the code: models.py class GalleryPicture(models.Model): title = models.CharField(max_length=200) img = WEBPField( verbose_name=_('Image'), upload_to=image_folder, null=True, blank=True, ) def __str__(self): return f'{self.title}' def get_absolute_url(self): return reverse('Galerie Überblick') class Meta: verbose_name_plural = 'GalleryPictures' I am also using a custom field for images, so all the uploaded pictures would be automatically converted into WEBP format: fields.py class WEBPFieldFile(ImageFieldFile): def save(self, name, content, save=True): content.file.seek(0) image = Image.open(content.file) image_bytes = io.BytesIO() image.save(fp=image_bytes, format="WEBP") image_content_file = ContentFile(content=image_bytes.getvalue()) super().save(name, image_content_file, save) class WEBPField(models.ImageField): attr_class = WEBPFieldFile urls.py path('content-manager/overview/gallery/<int:pk>/edit', EditGalleryImage.as_view(), name="Bild ändern") views.py class EditGalleryImage(UpdateView): model = GalleryPicture template_name = './pages/content_edit/edit_gallery_image.html' fields = ['title', 'img',] edit_gallery_image.html <div class="form-content"> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <input class="submit-button link-button" type="submit" value="Speichern" name="save-image"> <input class="submit-button link-button" type="submit" value="Löschen" name="delete-image"> </form> </div> My first approach was to create a … -
Elastic kibana with rest api
I am trying to use rest API in the kibana dev portal. but I am not getting the correct output. here I am attaching my file -
How do I prevent a duplicate entry on refresh for django model?
I am still learning Django and recently discovered that when I refresh my page it does a duplicate entry and was wondering how I might avoid this or link the function to the button possibly. Here is my views.py function def basketballPickup(request): # displays page and Pickup model form = PickupForm(data=request.POST or None) posts = Pickup.games.all() if request.method == 'POST': form_valid = form.is_valid() if form_valid: instance = form.save(commit=False) instance.save() return redirect() content = {'form': form, 'posts': posts} and here is my HTML template {% extends "Basketball/Basketball_base.html" %} {% block content %} <form method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit" name="Save_Pickup">Save Pickup Game</button> </form> <div id="pickup_table"> <table> {% for i in posts %} <tr> <th><p>Position:<p>{{ i.position}}</th> <th><p>Date:</p>{{ i.date}}</th> <th><p>Points:</p>{{ i.points}}</th> <th><p>Assists:</p>{{ i.assists}}</th> <th><p>Rebounds:</p>{{ i.rebounds}}</th> <th><p>Steals:</p>{{ i.steals}}</th> <th><p>Blocks:</p>{{ i.blocks}}</th> <th><p>Turnovers:</p>{{ i.turnovers}}</th> </tr> {% endfor %} </table> </div> {% endblock %} -
How to check if user is in many to many model django
i am trying to do permission for user where i defined my model like this class UserInstances(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,blank=True,null=True,unique=False) instance_name = models.CharField(max_length=150) instance_size = models.PositiveIntegerField(default=0) instance_objects = models.PositiveIntegerField(default=0) instance_map = models.TextField() instance_permission = models.ManyToManyField(User,related_name='instance_permission') def __str__(self): return f"{self.instance_name} instance for {self.user}" API code user = Token.objects.get(key=request.auth) if UserInstances.objects.get(id=2).instance_permission.exists(user) :// for demonstration print("access granted") Can you tell me how to check if user exist or not in many to many field object -
i need to take convert location coordinates to distance and then filter the queryset accordingly using django-filter
Following is the model which will be filtered in search query. Models.py class RentTypeChoices(models.IntegerChoices): DAILY = 0 HOURLY = 1 MONTHLY = 2 rent_type = models.PositiveSmallIntegerField( choices=RentTypeChoices.choices) title = models.CharField(max_length=256) available_from = models.DateField(default=datetime.date.today) category = models.ForeignKey( Category, related_name="rent_posts", on_delete=models.CASCADE) price = models.DecimalField(decimal_places=2, max_digits=6) # Need to convert below location coords to distance latitude = models.CharField(max_length=120) longitude = models.CharField(max_length=120) is_available = models.BooleanField(default=True) Filters.py from django_filters import rest_framework as filters from apps.embla_services.models import RentPost class RentPostFilters(filters.FilterSet): title = filters.CharFilter(lookup_expr="icontains") is_available = filters.BooleanFilter() rent_type = filters.ChoiceFilter(choices=RentPost.RentTypeChoices.choices) category__id = filters.NumberFilter() available_from = filters.DateFromToRangeFilter() price = filters.RangeFilter() # i need to filter this model by distance also # search query would contain the min or the maximum distance and i would need to filter # accordingly class Meta: model = RentPost fields = ["title", "is_available", "rent_type", "category", "available_from", "price"] i know how to convert the location coords between 2 points by using this post Getting distance between two points based on latitude/longitude. however how to exactly use this knowledge to filter the location coordinates to get the distance is my problem. following the example search request from client side {{baseUrl}}/rent/search-posts?title=k&rent_type=0&category=14&available_from_after=2022-04-`26&available_from_before=2022-10-05&price_min=40.00&price_max=45.00&distance_max = 5&distance_min=1` everything else is being done perfectly, only problem is distance part. client need … -
django rest framework APITestCase including file fields
How can I write a test for the following code snippet? I have trouble with handling files. Extra files are created in the media folder and also the test does not work properly. Searching was useless. # models.py class Book(models.Model): title = models.CharField(max_length=255, unique=True) author = models.ForeignKey(Author, related_name='books', on_delete=models.CASCADE) description = models.TextField(verbose_name='about book', blank=True, null=True, max_length=2000) cover = models.ImageField(default='ebook_pictures/default.png') slug = models.SlugField(unique=True) pdf = models.FileField(validators=[FileExtensionValidator(['pdf'])]) genres = models.ManyToManyField(Genre, related_name='books', blank=True) # serializers.py class BookSerializer(ModelSerializer): book_detail_url = HyperlinkedIdentityField(view_name='book-detail', lookup_field='slug', read_only=True) class Meta: model = Book fields = '__all__' extra_kwargs = {'slug': {'read_only': True}, } # views.py class BookViewSet(ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer lookup_field = 'slug' permission_classes = [IsAdminOrReadOnly] filter_backends = [filters.SearchFilter] search_fields = ['title', ] # urls.py router = DefaultRouter() router.register(r'books', BookViewSet, basename='book') # settings.py MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media/' # tests.py class BookViewSetTestCase(APITestCase): def test_book_create(self): pass -
When including resources DRF returns my soft deleted records
I have DRF API that supports including the books of an author in an authors get request. Our API has a soft delete system where Book(2) marked as deleted. But when I do the request below Book(2) is still included in the response. I would like to have only Book(1) in the response of this request. GET http://localhost/authors/2?include=books API returns to me: { "data": { "type": "Author", "id": "2", "attributes": {...}, "relationships": { "books": { "meta": { "count": 2 }, "data": [ { "type": "Book", "id": "1" }, { "type": "Book", "id": "2" } ] } } }, "included": [ { "type": "Book", "id": "1", "attributes": {...} }, { "type": "Book", "id": "2", "attributes": {...} } ] } If someone could just point me out in the right direction I would be really helpful. There is probably a function that I need to override somewhere but I can't seem to find it. -
how to make a chat application with django?
I ask for tips on making a chat application with django, what are the most important components to play my chat application using django? if there is a good article in your opinion, please archive the link in your answer. -
Page not found (404) “/home/aboozzee/Desktop/djangogirls/check/src/meida/accounts/signup” does not exist
i made a program using django, i got all right but when i try to enter to some pages i get this error, i tried Absolutely the same code on my Notebook using git clone from my github and everything worked ok. Notice that the Error i get just in on my Pc, one week ago everything worked well until on my Pc. My Code : accounts.urls from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('accounts/', include('django.contrib.auth.urls')), path('accounts/', include('accounts.urls', namespace='accounts')), path('admin/', admin.site.urls), path('jobs/', include('job.urls', namespace='jobs')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py from django.shortcuts import render, redirect from .models import Job from django.core.paginator import Paginator from .forms import ApplyForm, PostForm from django.urls import reverse from django.contrib.auth.decorators import login_required def job_list(request): job_list = Job.objects.all() paginator = Paginator(job_list, 5) # Show 5 Jobs Per Page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = {'jobs': page_obj} print(job_list) return render(request, 'job/job_list.html', context) def job_details(request, slug): job_details = Job.objects.get(slug=slug) if request.method == 'POST': form = ApplyForm(request.POST, request.FILES) if form. is_valid(): my_form = form.save(commit=False) my_form.job = job_details my_form.save() return redirect(reverse('jobs:job_list')) else: form = ApplyForm context = {'job': job_details, 'form': form} return … -
Python Django ImportError, cannot import name
I am having this issue with django project that has the following apps: Accounts Billing Bookings Notifications The error appears as soon as I add the following to notifications/models.py: import notifications.utils as U The following is the full log of the exception: D:\Noki\code\nokidepot_tcp\website\noki_proj>python manage.py runserver 192.168.1.103:8000 Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\jahanzeb\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\jahanzeb\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "D:\Noki\code\nokidepot_tcp\nokienv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\Noki\code\nokidepot_tcp\nokienv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "D:\Noki\code\nokidepot_tcp\nokienv\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "D:\Noki\code\nokidepot_tcp\nokienv\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "D:\Noki\code\nokidepot_tcp\nokienv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\Noki\code\nokidepot_tcp\nokienv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\Noki\code\nokidepot_tcp\nokienv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\Noki\code\nokidepot_tcp\nokienv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\jahanzeb\AppData\Local\Programs\Python\Python37-32\lib\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 "D:\Noki\code\nokidepot_tcp\website\noki_proj\accounts\models.py", line 13, in <module> from billing.views import charge_booking File … -
How to connect my amazon seller with django website
hey is it easy to connect amazon seller with my django, i try to fix every things inside my aws amazon like documentations and i register with Developer Central, but really i'm lost because and want some help like a easy step to follow for fixing it and inside django what i need to do it's my first time to connect api with django. Thank you -
How to search by choices with inmagik/django-search-views
For example, school grade 3. School table stores min and max grades. Elementary has K-5, Middle has 6-8, and High has 9-12. I have stored the grades as K, 1st, 2nd, etc. -
How Can I check if logged in user profile information is updated in django models
I am working on a project in Django where I have a Profile Model with a Foreign Key field (OneToOne Relationship with User Model) called applicant and a status field which is set to 'Update' at default. Other fields like surname and othernames are also included in the Profile Model. class Profile(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=10, null=True) othernames = models.CharField(max_length=30, null=True) status = models.CharField(max_length=30, default='Update', null=True) def save(self, *args, **kwargs): self.profilestatus = 'Updated' super().save(*args, **kwargs) def __str__(self): return f'{self.applicant.username}-Profile' I want the system to check every logged in user if their profile information are not Updated, they should be redirected to the Profile Update page to update their profile first else they should be redirected to view their updated profile. def index(request): user = request.user.is_authenticated if request.user.is_authenticated and Profile.objects.get(applicant==user, status== 'Update'): return redirect('user-profile-update') else: return redirect('user-profile') context = { 'check_profile_update':check_profile_update, } return render(request, 'dashboard/index.html', context) I have ModelForm with a save method with automatically updates the satus field in Profile Model to Updated any time a user updates his or her profile information. Someone should kindly help me on the best way of solving this issue. Thanks -
solucion a este error , [Errno 2] No such file or directory en python
enter image description here enter image description here.png si existe todo esta dentro del entorno -
Django-storages uploads to S3 causing Django to hang
How can I prevent blocking when uploading to S3 using django-storages? My webserver currently gets about 100TPS and I have 17 workers (8 core cpu). After a bit of investigation I believe it's user content being uploaded that causes my webserver to hang. Is there a way to use django-storages + S3 properly (that prevents the event loop from being blocked)? Or am I barking up the wrong tree? Or– do I simply need to continue scaling worker resources? -
Django Project database MongoDB deploy in Azure settings
I've completed the deployment of the Django project on Azure Web App. However, I am getting errors in DATABASES in settings.py In settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'db-name', 'CLIENT': { 'host': 'mongodb+srv://<username>:<password>@<atlas cluster>/<myFirstDatabase>?retryWrites=true&w=majority' } } } However, Azure is unable to establish a connection with MongoDB. Is there anybody who knows the proper approach for a Django project to connect to MongoDB in the Azure web application? I need some help. Anyone who can assist me would be much appreciated; I need assistance with this difficulty. -
how to connect or acquire a connection to a blob storage via outbound proxy
curl -v -X GET 'https://outboundproxy.xx.net:8443/<Container_name>/<SAS>Token' -H 'Host: Azurestorage.blob.core.windows.net' -H "Rest of the curl headers" We have a outbound proxy inplace and all of the external connection has to go via an 'https://outboundproxy.xx.net:8443'. Hence, In the above curl command i have used host header to pass the actual storage account base url. Now, I want to replicate it using the python Azure blob SDK module but I am not sure how to structure the account url parameter. Any pointer or hint will be helpful -
Understanding slow Django performance
My webserver is scaling and I'm using Sentry Performance to try and better understand where things are slow. One thing that I don't quite understand is where the slowness might be coming from when the total reported query times are dramatically different than the time it takes to get a response. For example, one of my endpoints is taking 40s to finally get a response to the user. You'll see the total response time took an incredible 44,000ms even though all the work was done in about 1s (which is still slow, but not 44s slow). -
set_password() function not working - DJANGO REST FRAMEWORK
Creating a new user works fine until I try to set the password of the new user. Every other data gets to the auth_user table except the password. What could be the cause and what's the solution? Link to github -
Error installation pip install mysqlclient [duplicate]
Bonjour après plusieurs recherche toutes la journée, je me permet de vous dérangez. Un problème d'installation de mysqlclient sur un projet django sur un S.E Ubuntu 20.04. J'ai tenté des solutions comme : pip install mysqlclient error Rien à faire sa marche pas. Mon dernier recours, je me tourne vers vous. Merci. Using cached mysqlclient-2.1.0.tar.gz (87 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [44 lines of output] mysql_config --version ['10.3.34'] mysql_config --libs ['-L/usr/lib/x86_64-linux-gnu/', '-lmariadb'] mysql_config --cflags ['-I/usr/include/mariadb', '-I/usr/include/mariadb/mysql'] ext_options: library_dirs: ['/usr/lib/x86_64-linux-gnu/'] libraries: ['mariadb'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/usr/include/mariadb', '/usr/include/mariadb/mysql'] extra_objects: [] define_macros: [('version_info', "(2,1,0,'final',0)"), ('__version__', '2.1.0')] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-39 creating build/lib.linux-x86_64-cpython-39/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-cpython-39/MySQLdb creating build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.linux-x86_64-cpython-39 creating build/temp.linux-x86_64-cpython-39/MySQLdb x86_64-linux-gnu-gcc … -
Django Test User Login With Factory And setUpClass
I am trying to test a user login with setUpClass, but the credentials of the saved user do not get accepted (403) during authentification although it works if I register the user manually (but I wanted to omit that for all functions so I do not have to do that, that's why I looked up setUpclass()) Am I missing something? test_register() works just fine. class AuthenticationTest(APITestCase): @classmethod def setUpClass(cls): super(AuthenticationTest, cls).setUpClass() cls.user_object = UserFactory.build() cls.user_saved = UserFactory.create() cls.client = APIClient() cls.base_url_login = reverse("api:login-list") cls.base_url_register = reverse("api:register-list") cls.base_url_logout = reverse("api:logout-list") cls.base_url_check_session = reverse("api:check-session-list") cls.faker_obj = Faker() def test_register(self): # Prepare data signup_dict = { 'username': self.user_object.username, 'password': 'test_Pass', 'email': self.user_object.email, } # Make request response = self.client.post( self.base_url_register, signup_dict ) # Check status response self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_data = response.json() self.assertEqual(response_data["success"], True) self.assertEqual(User.objects.count(), 2) # Check database new_user = User.objects.get(username=self.user_object.username) self.assertEqual( new_user.email, self.user_object.email, ) def test_login(self): # Prepare Data login_dict = { 'password': self.user_saved.password, 'email': self.user_saved.email, } # Make request response = self.client.post(self.base_url_login, login_dict) # Check status response self.assertEqual(response.status_code, status.HTTP_200_OK) response_data = response.json() self.assertEqual(response_data["success"], True) ... class UserFactory(django.DjangoModelFactory): class Meta: model = User username = Faker("user_name") email = Faker("email") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if …