Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to create a custom user in my Django application but I am facing some Unknown problem when I tried my custom user please somebody help me
##My django codes are: from django.contrib import admin from django import forms from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError from django.contrib.auth import get_user_model # Register your models here. from .models import MyUser class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label="password", widget=forms.PasswordInput) password2 = forms.CharField( label="password confirmation", widget=forms.PasswordInput) class Meta: model = MyUser fields = ('username', "email", "first_name", "last_name", "gender", "date_of_birth") def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise ValidationError("Password don't match") return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): passwrod = ReadOnlyPasswordHashField() class Meta: model = MyUser fields = ('username', "email", "first_name", "last_name", "gender", "date_of_birth", 'is_active', "is_admin") def clean_password(self): return self.initial["password"] class UserAdmin(BaseUserAdmin): form = UserChangeForm add_form = UserCreationForm list_display = ('username', 'email', 'first_name', 'last_name', 'is_admin', 'is_active') list_filter = ('is_admin',) fieldsets = ( (None, { "fields": ('username', 'email', 'first_name', 'last_name', 'is_admin', 'is_active', 'password', 'date_of_birth', 'gender'), }), ) add_fieldsets = ( (None, { "fields": ('username', 'email', 'first_name', 'last_name', 'is_admin', 'is_active', 'password1', 'password2', 'date_of_birth', 'gender'), }), ) search_fields = ('email',) ordering = ('email',) filter_horizontal = () User = get_user_model() admin.site.register(User, UserAdmin) ##my models.py from django.db import models … -
Get NGINX ip address in docker in Django settings.py for Django-debug-toolbar
I have a dockerized DRF project with installed NGINX in it. All works fine except one thing: Django debug toolbar requires INTERNAL_IPS parameter to be specified in settings.py. For docker I use this one: hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] + "1" for ip in ips] It also works fine but not with NGINX as NGINX use it’s own ip dynamically(probably?) definded inside or assigned by docker or anything else. I can get this ip from server logs: 172.19.0.8 - - [09/Oct/2020:17:10:40 +0000] "GET /admin/ HTTP/1.0" 200 6166 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 OPR/71.0.3770.228" and add it to setting.py: hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] + "1" for ip in ips] INTERNAL_IPS.append('172.18.0.8') but I expect that this ip might be different on different machines etc, so it is not reliable enough. So that question is -is it possible somehow to get NGINX docker ip in settings.py dynamically or fix docker-compose somehow??? docker-compose: version: '3.8' volumes: postgres_data: redis_data: static_volume: media_volume: services: web: build: . #command: python /code/manage.py runserver 0.0.0.0:8000 command: gunicorn series.wsgi:application --config ./gunicorn.conf.py env_file: - ./series/.env volumes: - .:/code - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles # ports: # - 8000:8000 … -
Python(Django) how to sort a list of objects by timestamp attribute
I have a list of objects 'posts' that I create with this python function, and I need to sort this list by timestamp attribute. def following(request): posts=[] follows=Follow.objects.all() for follow in follows: if follow.follower==request.user: posts_user=Post.objects.filter(user=follow.user) for post in posts_user: posts.append(post) return render(request, "network/following.html",{ "posts":posts }) If this was a QuerySet, I would have sorted by using this function: posts = posts.order_by("-timestamp").all() But this is a list so I cant use this function, it gives me this error: 'list' object has no attribute 'order_by' How can I sort this list by the timestamp so that the most recent post is the first? This is the Post class in models.py class Post(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="user_post") text=models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) likes=models.IntegerField(default=0) My idea was to convert the list to a QuerySet, but I don't know how to do it. Thank you! -
How can I make Django to save users using DynamoDB?
I can't find a way to configure DynamoDB as the database for my application, apparently there is no built-in way to configure DynamoDB as the ENGINE for the project, is there a solution to bring my users to a DynamoDB table? I'm looking for a way to authenticate users and superusers withouth having to implement an authentication system to do this. -
Django - how to find out which ForeinKey object made an instance appear in the filter's result
Imaging I have two models like this: class ExportProfile(Model): name = CharField() other_fields = ... class ExportFile(Model): exported_by = ForeignKey(ExportProfile) file_type = CharField() other_fields = .... e1 = Export(name='export1', ...) ef1 = ExportFile(exported_by=e1, file_type='zip', ...) ef2 = ExportFile(exported_by=e1, file_type='zip', ...) ef3 = ExportFile(exported_by=e1, file_type='zip', ...) I'm filtering it like this and I will receive 3 ExportProfile's objects(because I don't want it to be distincted): ExportProfile.objects.filter(exported_by__file_type='zip') The question is, how can I know which one of these objects belongs to which ExportFile? I want to write a serializer for ExportProfile model, so I need to know the exact ExportFile that caused this ExportProfile to be appeared in the filter result. -
Elasticsearch + django: Unknown mimetype, unable to deserialize: text/html
I have browsed for this error on Stackoverflow and elsewhere, but nothing helps. I have installed django-elasticsearch-dsl and added it to my INSTALLED_APPS. In my settings, I have: ELASTICSEARCH_DSL={ 'default': { 'hosts': 'localhost:9200' }, } Next, I have a 'documents.py' file where the logic for Elastic search resides. When I try running python manage.py search_index --rebuild, I get this error: elasticsearch.exceptions.SerializationError: Unknown mimetype, unable to deserialize: text/html I don't know if I understand correctly how to run the ES server. I have tried to run the local server on port 9200 but the issue persists. -
Displaying 404 error handling page using django
I am trying to handle a 404 http response error on the site. I want my 404.html content to be displayed, but for some reason when I run my local host I do get the response displayed, but my site doesn't look the same as in my contents aren't being displayed as they should. I don't know why this is happening, but I want to make sure I am properly calling in my handler. Any suggestions would be appreciated. My views.py def handler404(request, exception): return render(request, 'webpage/404.html') My 404.html {% extends "webpage/base.html" %} {% block content %} {% load static %} <h1>404 Error</h1> {% endblock %} My Url.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('webpage.urls')), ] handler404 = views.handler404 -
Datatable Jquery AJAX with Django Paginator
I would like to use DataTable Jquery, with order and search options, from a Django table with Paginator. I had this error: Page or contactstruckerCharge is not a JSON serializable. It is my Django View: charges_asign=TruckerCharge.objects. paginator = Paginator(charges_asign, 30) page = request.GET.get('page') try: contactstruckerCharge = paginator.page(page) except PageNotAnInteger: contactstruckerCharge = paginator.page(1) except EmptyPage: contactstruckerCharge = paginator.page(paginator.num_pages) return HttpResponse(json.dump(list(contactstruckerCharge)), content_type='application/json') I tried with the next code, however it not working because get_json() is not a object valid for item return HttpResponse(json.dumps([item.get_json() for item in contactstruckerCharge.object_list]) , content_type='application/json') It is the frontend: $('#charges_table').DataTable({ "scrollY": "500px", "scrollCollapse": true, "order": [[ 0, "desc" ]], rowReorder: { selector: ':last-child' }, "ajax": { url: "/charge/myChargesAssingAJAX/", method: 'post', data: function(args) { return { "args": JSON.stringify(args), 'csrfmiddlewaretoken': '{{ csrf_token }}' }; } }, "search": "Buscar:" } }); $('.dataTables_length').addClass('bs-select'); }); Anyway, I do not know if is the correct way to do it. Thanks. -
Objects not being displayed in Django Admin when Foreign key is Null
I have a Model "Item" that has a field "req_item", that's a nullable foreign key. Everything seems to working fine, but when the "req_item" field is null, the object is not displayed in django admin altogether. Here's the image for reference: All the "req_item" filed values are null in DB at the moment, so none of the objects are displayed. If I assign a valid req_item value to an object in the DB, then only that object is displayed. How can I fix this issue. Here's my admin.py -
How to remove extra whitespaces on django rest serializers
I have this problem atm where you serializer an object in django and it appears something like that. {"title": " remove all spaces "} Within the serializer you can set extra_kwargs to trim fields. The results is the next {"title": "remove all spaces"} Is there a way to remove those extra white spaces between the words "remove" and "all"?? Here is the serializer example: class exampleSerializer(serializers.ModelSerializer): class Meta: model = Example fields = ("title", ) extra_kwargs = {"content": {"trim_whitespace": True}} -
error: failed to push some refs to 'https://github.com/loliadus/djangolocallibrary.git'
So I'm trying to update the addition of new folders and files to a git repository. After cloning the repository and copying those folders and files to the repository, I run the following commands C:\Users\Ben\Documents\djangoprojects\djangolocallibrary>git add -A C:\Users\Ben\Documents\djangoprojects\djangolocallibrary>git status On branch main Your branch is up to date with 'origin/main'. Changes to be committed: (use "git restore --staged <file>..." to unstage) modified: .gitignore new file: catalog/__init__.py new file: catalog/admin.py new file: catalog/apps.py new file: catalog/forms.py new file: catalog/migrations/0001_initial.py new file: catalog/migrations/0002_bookinstance_borrower.py new file: catalog/migrations/0003_auto_20201007_2109.py new file: catalog/migrations/__init__.py new file: catalog/models.py new file: catalog/static/css/styles.css new file: catalog/templates/base_generic.html new file: catalog/templates/catalog/author_confirm_delete.html new file: catalog/templates/catalog/author_detail.html new file: catalog/templates/catalog/author_form.html new file: catalog/templates/catalog/author_list.html new file: catalog/templates/catalog/book_confirm_delete.html new file: catalog/templates/catalog/book_detail.html new file: catalog/templates/catalog/book_form.html new file: catalog/templates/catalog/book_list.html new file: catalog/templates/catalog/book_renew_librarian.html new file: catalog/templates/catalog/bookinstance_list_borrowed_all.html new file: catalog/templates/catalog/bookinstance_list_borrowed_user.html new file: catalog/templates/index.html new file: catalog/tests/__init__.py new file: catalog/tests/test_forms.py new file: catalog/tests/test_models.py new file: catalog/tests/test_views.py new file: catalog/urls.py new file: catalog/views.py new file: locallibrary/__init__.py new file: locallibrary/asgi.py new file: locallibrary/settings.py new file: locallibrary/urls.py new file: locallibrary/wsgi.py new file: manage.py new file: templates/logged_out.html new file: templates/registration/login.html new file: templates/registration/password_reset_complete.html new file: templates/registration/password_reset_confirm.html new file: templates/registration/password_reset_done.html new file: templates/registration/password_reset_email.html new file: templates/registration/password_reset_form.html C:\Users\Ben\Documents\djangoprojects\djangolocallibrary>git commit -m "Version 1.0 moved into Github" [main a706353] Version … -
Django Project 'NodeNotFoundError' After Upgrading and Then Immediately Going Back to Previous Version
I upgraded Django in my virtualenv from 2.2 to 3.1 on accident and then tried to revert to 2.2 by running pip3 install django==2.2. When I tried running the server again I got a NodeNotFoundError suggesting that there was a missing migration: > NodeNotFoundError(self.error_message, self.key, origin=self.origin) > django.db.migrations.exceptions.NodeNotFoundError: Migration > auth.0013_auto_20201005_2333 dependencies reference nonexistent parent > node ('auth', '0012_alter_user_first_name_max_length') So it looks like I'm missing migration 0012 in my auth app migrations. I checked the latest auth migration (django.contrib.auth.migrations) expecting 0013 to be latest, but it doesn't even exist. The most recent is 0011. So I'm getting a dependency error from a migration that doesn't exist itself? Well this is a headache and I don't want to drop the database but it seems like the easiest decision at this point. I set up a new virtualenv with django 2.2 and a new database, deleted all migrations in a copy of the project to start clean. I run python3 manage.py migrate on the new database and get the same exact NodeNotFoundError above where migration auth.0013 depends on auth.0012. Maybe some migrations were created with 3.1 and deleted when 2.2 was reinstalled? I don't think I even ran migrations when 3.1 was … -
python df to html result is not table format
I am trying to sent some values(server_data) to a basic webpage. I reformated my values as a Dataframe and converted to html format. But when i want to display my table,I just see html codes not table view. What am i missing? Phyton codes: def vip_result(request): (---) server_data{"SERVER_IP":result1,"PORT":result2,"SERV.STATE":result3,"OPR. STATE":result4} df=pandas.DataFrame(server_data) df=df.to_html return render(request, 'vip_result.html', {"df": df}) Html site:(vip_result.html) {{df}} Result page` <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>SERVER IP</th> <th>PORT</th> <th>SERV.STATE</th> <th>OPR. STATE</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>10.6.87.17</td> <td>7777</td> <td>UP</td> <td>ENABLED</td> </tr> <tr> <th>1</th> <td>10.6.87.18</td> <td>7777</td> <td>UP</td> <td>ENABLED</td> </tr> <tr> <th>2</th> <td>10.6.87.21</td> <td>7777</td> <td>UP</td> <td>ENABLED</td> </tr> <tr> <th>3</th> <td>10.6.87.21</td> <td>7780</td> <td>UP</td> <td>ENABLED</td> </tr> <tr> <th>4</th> <td>10.6.87.23</td> <td>7781</td> <td>UP</td> <td>ENABLED</td> </tr> <tr> <th>5</th> <td>10.6.87.23</td> <td>7783</td> <td>UP</td> <td>ENABLED</td> </tr> </tbody> </table>`: Result page that I expext -
How do I load an image by URL in the Django model, and then how do I write a form and a view to resize the images?
I did the part for adding the usual image, with the rest I find it difficult to hand over the work to the teacher on Monday, I would be grateful if you could help I need a django app that: You can add an image by entering a link to a file from the Internet, or by selecting a file from your computer. If neither option was entered when the form was submitted, or both are entered, an error message should be displayed. After a successful download, we are taken to the image page. Initially, the image is displayed here in its original size. New dimensions can be set through the form. After submitting the form, the page should refresh and display the image that fits into the new dimensions. The image must be resized physically on the backend, while the original image must be preserved. You can specify only the width, only the height, or both. The aspect ratio of the image must be maintained. Code here - 'https://pastebin.com/q0h3M6PR' -
ChoiceField Django
I wonder whether there is a way to make a list of values like that but without having to write all these manually because it will take a lot of space for 100+ values. Is there a function that will make a list like that for me? I need to have choices from 18-100. AGE_CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ) -
Django Rest Framework serialization of viewset response
I have the following ViewSet in Django Rest Framework: class FilterProductsViewSet(viewsets.ViewSet): permission_classes = (permissions.IsAuthenticated,) @transaction.atomic def post(self, request): from inventory.models import Product, Stock size = len(request.data) response = get_filter(request.data, size) return Response(response) I want the response to be paginated, but I haven't found documentation on how to do it with a ViewSet instance. I'll appreciate your help. -
Getting extra_content value in Django admin?
How to get extra_content value Django admin? I need a currencies_count is a value of length of filtered queryset for my numeration function? My code: class OrderAdmin (admin.ModelAdmin): indexCnt = 0 list_display = ['numeration', 'client', 'shipping_data', 'receipt', 'status', 'created', 'updated'] list_editable = ('status',) search_fields = [field.name for field in Order._meta.fields] list_filter = ('status',) def changelist_view(self, request, extra_context=None): response = super(OrderAdmin, self).changelist_view(request, extra_context) filtered_query_set = response.context_data["cl"].queryset currencies_count = filtered_query_set.distinct().count() extra_context = { 'currencies_count': currencies_count, } response.context_data.update(extra_context) return response def numeration(self, obj): count = # I NEED TO GET 'currencies_count' VALUE HERE if self.indexCnt > 1: self.indexCnt -= 1 else: self.indexCnt = count return self.indexCnt numeration.short_description = '#' -
Django Aggregation Question - Strange behavior
I have a query set of activities which has an associated user_id on on that model. In this example, I have a query set containing the below based on this statement activities.values('user_id').annotate(Min('duration')) [ {'user_id': 149026, 'duration__min': Decimal('480.0000')}, {'user_id': 149026, 'duration__min': Decimal('454.0000')}, {'user_id': 149026, 'duration__min': Decimal('360.0000')}, {'user_id': 149027, 'duration__min': Decimal('420.0000')} ] I need to grab the activity for each user_id that has the lowest duration. I'm a bit confused as to why the following statement below returns to me what I want activities.values('user_id').annotate(Min('duration')).order_by('user_id') [ {'user_id': 149026, 'duration__min': Decimal('360.0000')}, {'user_id': 149027, 'duration__min': Decimal('420.0000')} ] Why would the order_by("user_id") clause return me the lowest duration activity for a specific user. Also, shouldn't the value clause preceding the annotate lead the returned query to have one annotated result for each unique user_id? -
Is this intended order of operations for this Django template tag conditional correct?
In basic terms, this is the what I am looking for {% if not A or (B and C == D) %} In a Django template tag (unable to use parentheses), is this the same result? {% if not A or B and C == D %} Thank you! -
When migrating Django to deployment i get this error why?
On my local machine there is no issue. Everything runs perfectly. Even python manage.py check --deploy brings up no issues on my local . But when I run makemigrations on my external server for deployment it gives me this error: Traceback (most recent call last): File "/opt/pyapps/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "Report_report" does not exist LINE 1: SELECT "Report_report"."id" FROM "Report_report" ORDER BY "R.. https://pastebin.com/L0waK5Nq -
Django Channels Websocket group name
Sorry for bad English :( I want to create notification system per user. User has own group/room and every notification go to specific user's notification room. Every time when user connect to websocket, user creates the same id of user. self.scope["user"]. Therefore only user_notification_1 group name was created. How it is possible to create group name depending on user? I use application = ProtocolTypeRouter( { "websocket": AuthMiddlewareStack(URLRouter(websocket_urlpatterns)), } ) Code: import json from channels.generic.websocket import WebsocketConsumer class NotificationConsumer(WebsocketConsumer): async def connect(self): self.user = self.scope["user"] if self.user.is_authenticated: self.room_group_name = f"user_notification_{self.user.id}" else: self.room_group_name = "anonymous" await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_name) async def receive(self, text_data=None, bytes_data=None): self.user = self.scope["user"] if self.user.is_authenticated: await self.send( text_data=json.dumps({"message": "pong"}) ) else: await self.send( text_data=json.dumps({"type": "error", "code": "UserNotAuthenticated"}) ) async def new_chat_message(self, event): await self.send(text_data=json.dumps(event.get("data"))) async def connect_successful(self, event): await self.send(text_data=json.dumps(event.get("data"))) -
Access ManyToMany relation from model property in Django
I have a Loan model that has some relationships, one of which is a many to many with a Resource model (the items our borrower is loaning). I'd like to add a derived property to the loan that does a quick check on the status of the loan's various resources. But whenever I try to access the loan's resources from within this property, I just get back None. It works fine for the one to one relationships, just not many to many. class Loan(models.Model): borrower = models.ForeignKey('Borrower', on_delete=models.PROTECT) resources = models.ManyToManyField('Resource', through='LoanedResource', blank=True) start_date = models.DateTimeField() due_date = models.DateTimeField() @property def is_closed(self): print(self.borrower) # Works! print(self.resources) # None :( print(self.loanedresources_set) # None :( print(LoanedResource.objects.filter(loan = self.id)) # This works, but I believe it bypasses prefetch_related, so gets really slow. # Return my calculated value here If this can't work, anyone have ideas on how to create derived property with many to many relationship that takes advantage of prefetch_related? Thanks! -
django: how to merge a class based view with a function based view
for some reason i wanted to use the django class based form view "PasswordResetView" in my template that already has a function based view which is the home view, so i thought that i should copy paste the "PasswordResetView" from django's source code in my views.py file and change what is needed but i always face some errors because i'm not familiar with class based views here is my view in my views.py file: def home(request): user = request.user signin_form = SigninForm() signup_form = SignupForm() if 'signin_form' in request.POST: signin_form = SigninForm(request.POST) if signin_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) elif user is None: messages.error(request, 'ُEmail or password is incorrect') if 'signup_form' in request.POST: signup_form = SignupForm(request.POST) if signup_form.is_valid(): signup_form.save() full_name = signup_form.cleaned_data.get('full_name') email = signup_form.cleaned_data.get('email') raw_password = signup_form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) context = {'signin_form': signin_form,'signup_form': signup_form} return render(request, 'main/home.html', context) here is the "PasswordResetView" from django's source code: from django.urls import reverse, reverse_lazy from django.contrib.auth.tokens import default_token_generator from django.views.generic.edit import FormView from django.views.decorators.csrf import csrf_protect from django.utils.decorators import method_decorator class PasswordContextMixin: extra_context = None def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'title': self.title, **(self.extra_context or {}) }) return … -
Permission clashes with a builtin permission [django-audiofield]
I'm trying make audiofield with django-audiofield... in my model.py i have import os from audiofield.fields import AudioField from django.conf import settings from django.db import models class AudioFile(models.Model): name = models.CharField(max_length=150, blank=False, verbose_name=('audio name'), help_text=('audio file label')) audio_file = AudioField(upload_to='upload/audiofiles', blank=True, ext_whitelist=('.mp3', '.wav', '.ogg'), verbose_name=('audio file')) def audio_file_player(self): if self.audio_file: file_url = settings.MEDIA_URL + str(self.audio_file) player_string = '<ul class="playlist"><li style="width:250px;">\ <a href="%s">%s</a></li></ul>' % (file_url, os.path.basename(self.audio_file.name)) return player_string audio_file_player.allow_tags = True audio_file_player.short_description = ('Audio file player') class Meta: permissions = ( ('can_view_audiofile', ('Can see AudioFiles')), ) But all the time I have ERROR: *ERRORS: audiofield.AudioFile: (auth.E005) The permission codenamed 'view_audiofile' clashes with a builtin permission for model 'audiofield.AudioFile'.* This Meta class in model is from documentation django-audiofield and I installed all apps in settings. -
psycopg2.errors.UndefinedTable: relation "sso_server_consumer" does not exist
I am working on implementing Django-Simple-SSO to our python based platform. I am following this blog to implement SSO: https://medium.com/@MicroPyramid/django-single-sign-on-sso-to-multiple-applications-64637da015f4 This code is the step number 3 on the server side of django-simple-sso. from simple_sso.sso_server.models import Token, Consumer Consumer.objects.create(public_key='your_application_public_key', private_key='your_application_private_key', name='your_application_name') psycopg2.errors.UndefinedTable: relation "sso_server_consumer" does not exist -- this is the error I am getting as soon as I run the above code in django shell. Can someone please help me on how to solve this error? Thank you