Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: login() takes 1 positional argument but 2 were given.Exception Value: login() takes 1 positional argument but 2 were given
I have written a login view using build-in auth ,django auth.login() gives above error my code. from django.contrib.auth.models import User from django.contrib.auth import authenticate,logout,login def loginpage(request): if request.method == "POST": user_name = request.POST.get("username") password = request.POST.get("password") user = authenticate(request, username=user_name, password=password) if user is not None: login(request, user) return redirect("dashboard") return render(request, "loginhtml.html") -
Why does is not entering to the right url?
I am making a project in school, making a site. when i click on nvbar its enter to the right URL but when i enter to another category its doesn't work. for example: if i enter to login: http://127.0.0.1:8000/login/ if i enter to register after login: http://127.0.0.1:8000/login/register and i need it to enter: http://127.0.0.1:8000/register Code: URLS: urlpatterns = [ path('admin/', admin.site.urls), path('', home_screen_view, name="home"), path('register/', registration_view, name="register"), path('logout/', logout_view, name="logout"), path('login/', login_view, name="login"), path('account/', account_view, name="account"), path('Sourcesofknowledge/', Sourcesofknowledge_view, name="Sourcesofknowledge"), path('customersatisfactionsurvey/', customersatisfactionsurvey_view, name="customersatisfactionsurvey"), ] nvbar: <div class="w3-top"> <div class="w3-bar w3-black w3-card w3-left-align w3-large"> <a class="w3-bar-item w3-button w3-hide-medium w3-hide-large w3-right w3-padding-large w3-hover-white w3-large w3-red" href="javascript:void(0);" onclick="myFunction()" title="Toggle Navigation Menu"><i class="fa fa-bars"></i></a> {% if request.user.is_authenticated %} <p>Hello, {{request.user.username}}</p> <a href="" class="w3-bar-item w3-button w3-padding-large w3-white">Home</a> <a href="#" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">Medicinal stock</a> <a href="Sourcesofknowledge" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">Sources of knowledge</a> <a href="customersatisfactionsurvey" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">Satisfaction Survey</a> <a href="logout" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">Logout</a> <a href="account" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">account</a> {% else %} <a href="" class="w3-bar-item w3-button w3-padding-large w3-white">Home</a> <a href="login" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">Login</a> <a href="register" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">Registry</a> <a href="Sourcesofknowledge" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">Sources of knowledge</a> {% endif %} </div> </div> -
Failed to load response data: css and js resources work on one url only
I have a website that looks like this: localhost:8000: https://i.stack.imgur.com/Miz9M.png It contains a search feature that works, but when the page is rendered the style does not load. This is how the page looks when searching for all schools that have a postcode that starts with 30: localhost:8000/find: https://i.stack.imgur.com/5qdyA.png views.py: page = f'{ROOT_DIR}/templates/tst/index.html' @api_view(['GET']) def get_data(request): schools = School.objects.all() return render(request, page, {'schools': schools}) @api_view(['GET']) def filter_view(request, property, filter, search): property = __translate_property(property) filter = filter.replace(" ", "").lower() kwargs = { '{0}__{1}'.format(f'{property}',f'{filter}'):f'{search}' } schools = School.objects.filter(**kwargs) return render(request, page, {'schools': schools}) Both methods use the same index.html. When inspecting the network from browser side (url:http://localhost:8000/find/Postcode/Starts%20with/30?), the css files and js script files cannot be found with error Failed to load response data. No data found for resource with given credential. -
dockerfile with django in visual studio code won't launch due to path not found
I am following a tutorial from visual studio code on creating a docker web app to run my python script in. for your information it is visible in the following link: https://code.visualstudio.com/docs/containers/quickstart-python I followed the django tutorial before this on installing it correctly and tested it so that it works. After allowing vs code to create all my necessary files, i tried to run it via my launch.json file. { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "runserver" ], "django": true, "justMyCode": true }, { "name": "Docker: Python - Django", "type": "docker", "request": "launch", "preLaunchTask": "docker-run: debug", "python": { "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/app" } ], "projectType": "django" } } ] } when i try this, i instantly get returned: > docker build --rm --pull -f "H:\Dockerfile" --label "com.microsoft.created-by=visual-studio-code" -t "h:latest" "H:\" < unable to prepare context: path "H:\"" not found The terminal process failed to launch (exit code: 1). I installed everything on my H drive, and after this error I added the H to my … -
How to handle django.http.response.StreamingHttpResponse or map object for testcase
I have test case which response is StreamingHttpResponse, not normal HttpResponse (it downloads the csv file) For example normal response, self.assertContains(response, "Testname") self.assertNotContains(response, "NoMisstake") However how can I do the same thing for StreamingHttpResponse? I reseached and found out response.stream_content is map object. It could be the clue??? -
Django {%url 'index2:Redirect' %} have error occurred
class R_View(RedirectView): pattern_name = 'first:login' query_string = True def get(self, request, *args, **kwargs): print(request.path) return super(R_View, self).get(request, *args, **kwargs) def login(requset): return render(requset, 'login.html') urlpatterns = [ path('2/', views.login, name='first'), path('f/', views.R_View.as_view(), name='Redirect'), urlpatterns = [ path('gb1/', include(('background.urls', 'first'), namespace='index2')) When I input 127.0.0.1:8000/bg1/2 Will report an error:IndexError: pop from empty list I think the hint is that there is a problem in this line, but I don't know exactly where the problem is:{%url 'index2:Redirect' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>RedirectView</title> </head> <body> <br> <a href="{%url 'index2:Redirect' %} ?k=10">Go</a> </body> </html> -
Localization of the model with a tree-like structure
I'm new to python/django development and I'm stuck. I'm making a project on Django 4.0.4. I have a tree table in a SQLite database. In the admin panel, I configured it using the DraggableMPTTAdmin class from mptt. I also want to localize the fields of this table. QUESTION: How can I combine the DraggableMPTTAdmin class with the TranslationAdmin class? my_app/models.py from django.db import models from mptt.models import MPTTModel, TreeForeignKey from django.db.models import CharField class NonStrippingCharField(CharField): """A TextField that does not strip whitespace at the beginning/end of it's value. Might be important for markup/code.""" def formfield(self, **kwargs): kwargs['strip'] = False return super(NonStrippingCharField, self).formfield(**kwargs) class CategoriesAndAreas(MPTTModel): name = NonStrippingCharField(max_length=150, unique=False) is_category = models.BooleanField() parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') def __str__(self): return self.name def __unicode__(self): return self.name class MPTTMeta: order_insertion_by = ['name'] class Meta: verbose_name = "Category or area" verbose_name_plural = "Categories and areas" my_app/translations.py from modeltranslation.translator import register, TranslationOptions from .models import CategoriesAndAreas @register(CategoriesAndAreas) class CategoriesAndAreasTranslationOptions(TranslationOptions): fields = ('name',) my_app/admin.py + DraggableMPTTAdmin from django.contrib import admin from mptt.admin import DraggableMPTTAdmin from .models import CategoriesAndAreas admin.site.register(CategoriesAndAreas, DraggableMPTTAdmin, list_display=( 'tree_actions', 'indented_title', 'is_category', ), list_display_links=( 'indented_title', ), ) The table has a tree structure with the ability to drag and drop. The form … -
Can i use Chart js for long data?
In django App for visualization , for long data what i can use? Chart JS , Matplotib?.... Please recommendation exemple value for one point : 0;-0.0110227457430789;-0.0117428254241928;-0.0125132024365239;-0.0120122425942302;-0.0121398995885254;-0.0127606573714123;-0.0123882233559148;-0.0126683380476791;-0.0125534489771807;-0.0114614833910938;-0.0139670311717919;-0.0117059991385652;-0.0127469146854689 -
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