Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python/Django - Set new password
I'm new at django and got problem with change password, I got no errors but the new password does not save and dont redirect me either? Here is my form.py: from django import forms from django.contrib.auth import get_user_model from django.db.models import Q class NewPasswordForm(forms.Form): error_messages = { 'old_password' : ("Your old password was entered incorrectly, Please enter it again"), 'password_mismatch' : ("The two password fields didn't match"), } old_password = forms.CharField(label='Current Password', widget=forms.PasswordInput) new_password1 = forms.CharField(label='New Password', widget=forms.PasswordInput) new_password2 = forms.CharField(label='Confirm New Password', widget=forms.PasswordInput) field_order = ['old_password', 'new_password1', 'new_password2'] def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_old_passpord(self): # Validate that the old_password field is correct. if not self.user.check_password(old_password): raise forms.ValidationError( self.error_messages['old_password'], code = 'old_password' ) return old_password def clean_new_password2(self): old_password = self.cleaned_data.get('old_password') password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if password1 and password2 and password1 != password2: if password1 == old_password: raise ValidationError( self.error_messages['password_mismatch'], code = 'password_mismatch' ) return password2 def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user Here is my view.py: from django.shortcuts import render, redirect from .forms import NewPasswordForm from .models import User from django.contrib.auth import authenticate, login, logout, update_session_auth_hash #Don't forget login_required def user_change_password_view(request): form = NewPasswordForm(request.POST or None) if … -
ImportError: No module named 'ronshome.wsgi'
I am completing these steps to setup my first Django web site. I've made it to the "Test your Django project" section. The command python3 manage.py runserver 192.168.0.53:8080 runs successfully. I am able to browse / navigate the new web site. I've been unable to make the next command uwsgi --http :8000 --module mysite.wsgi work. I've tried to slightly modify it to match my venv: uwsgi --http :8000 --module ronshome.wsgi:application This creates the error: ImportError: No module named 'ronshome.wsgi' I re-confirmed the success of: pip3 install uwsgi which outputs: Requirement already satisfied: uwsgi in ./ronshome/lib/python3.5/site-packages I did the command find . -name \*.txt -print The file ronshome.wsgi does not exist within website folder. I used ronshome as the name of the venv. I am not understanding how to proceed with the deployment of uWsgi -
Make STATIC_ROOT depend on domain
In my Django application I am using the staticfiles app in conjunction with Whitenoise. My web server is accessible via two domains and I would like to serve different static files for each. My idea was that www.my_domain.com/static/ would serve up, say, the files in os.path.join(BASE_DIR, "staticfiles/my_domain/"), and vice-versa for www.my_other_domain.com/static/. What is the best way of achieving this? I have thought of two solutions: Subclass the places in which STATIC_ROOT is accessed, so that it takes the domain into account Use nginx to route www.my_domain.com/static/my_domain/ to www.my_domain.com/static/ Thank you! -
Django "Performing System Checks" is running very slow
Out of nowhere I'm running into an issue with my Django application where it runs the "Performing System Checks" command very slow. If I start the server with python manage.py runserver It takes more then a minute or two for the server to actually start up. After that it works fine until I make an update and then it restarts the server and goes through the process of "performing system checks" again. I'm running Django 2.1.1. I read on a few other posts that this has something to do with installing MySQL version 5.7, which is something I did recently, but I went through and uninstalled it as completely as I can using HomeBrew and removing other references. This pretty much makes development impossible at this point as I can't be waiting a few minutes between every change. -
I want to add class to Django template
I want to add class to Django template.I wrote template, {{ name }} {{ age }} I want to add test class to these 2 input form.I do not understand it can be done only Django&Python.How can I do it?I really cannot understand it. -
Testing Angular and Django Rest Framework apps
Let's say I have a frontend application written in Angular and a backend application written in Django and Django Rest Framework. I created unit tests for backend application (with pytest) and I'm about to create some functional tests for the frontend application. The thing is that the frontend app needs access to the backend app in order to work correctly. I can write some mocks to handle that, but I am not sure if this is the best way to do that. My question is, what is the best way to handle that? Should I use a single git repo for both applications or maybe a better way is to use two repositories, but then how to handle the tests for frontend application? I was also thinking about using selenium with pytest, but then I would have to use a single repository. I am a little bit confused and would really use some good advice. Thanks! -
What is the best solution to create user notifications on adding new record into model with Django Channels?
There is an object that has a comment option, as there is an option to subscribe to notifications on adding/deleting/editing comments to this object. I came up with one solution - each object is a group where subscribed users are stored and when there is a removal/addition/edition of a comment to this group happens, a notification is sent to the group of this object. So, is this right solution? -
How to capture a DOM click with Python / Django?
I want to create a simple Tic-Tac-Toe game with Python. It will be just a 3x3 table. The question is how to capture a click when user clicks on a specific cell? Do I need to use JavaScript / jQuery for this ar can it be done with Python? Thanks in advance! -
JWT configuration in Django
I'm developing a Django application for Windows with Pyhton 2.7.15. I need to implement an authentication mechanism where if a user has a specific JWT token, he can browse the application (in other words, I just need to verify the token and not generate it). The token is very easy and maybe will be something like this: Header { "alg": "HS256", "typ": "JWT" } Payload { "iss": "customIssuer" } Signature HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret ) To implement the verification's service, I installed the Rest framework JWT tools and I modifyed my setting.py in this way: ... REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.TokenAuthentication' ), } JWT_AUTH = { 'JWT_ISSUER': 'customIssuer' } ... then I modifyed the urls.py: ... from rest_framework_jwt.views import verify_jwt_token urlpatterns = [ ... url(r'^api-token-verify/', verify_jwt_token), ... ] Finally, using Postman, I tryed to send a POST request with the above token but I get a 400 Bad Error error with this body: { "non_field_errors": [ "Invalid payload." ] } Investigating about the reason I realize that I must add the username claim in the payload but I don't want to. It's possible to configure the application to ignore that claim? -
Converting a video with Celery and ffmmpeg with Django
https://github.com/pstreck/django-videokit I cloned this repo, installed the requirements, successfully ran the server but the app just copies the source video, creates a thumbnail and renames it even after passing the ffmpeg options '-s' '300:300' and '-vf' 'scale=300:300'. + command = ['ffmpeg', '-y', '-i', source_file, '-s', '300:300', temp_file] process = subprocess.Popen(command, stdin=subprocess.PIPE) process.wait() processed_file = os.path.join(base, media_root, file_name) f = File(open(temp_file, 'r')) default_storage.save(processed_file, f) f.close() os.remove(temp_file) -
Nested validation in Django Rest Framework
Using django rest framework I want to validate fields. Correct input request: { test_field_a: {test_field_c: 25}, test_field_b: {} } My serializers.py (I don't have any associated models and the models.py itself): from rest_framework import serializers class TestSerializer(serializers.Serializer): test_field_a = serializers.JSONField(label='test_field_a', allow_null=False, required=True) test_field_b = serializers.JSONField(label='test_field_b', required=True) test_field_c = serializers.IntegerField(label='test_field_c) Wrong input request (which should state that int field is required) : { test_field_a: {test_field_c: 'wrong'}, test_field_b: {} } Now test_field_a and test_field_b are validated as required. But how to make validation of fields on different levels of the request? (in this case test_field_c) -
Using same foreign key twice in a model in django as different fields
I have a model Transaction Type that has credit_account and debit_account fields. Both fields are foreign keys from the Account model. Is it good idea to have them like the way I have implemented below? class TransactionType(models.Model): name = models.CharField(max_length=255) organization = models.IntegerField(null=False, blank=False) credit_account = models.ForeignKey(Account) debit_account = models.ForeignKey(Account) -
Request for external site in Django / Ajax
I have an application developed in Django and I am trying to implement the code below directly in the code to query in a public API in Brazil. However, the following error is occurring: Cross-origin request blocked: Same Origin Policy prevents the remote resource from reading at https://www.receitaws.com.br/v1/cnpj/[object%20Object]. (Reason: CORS 'Access-Control-Allow-Origin' header is not present). There are several implementations available for languages like PHP but for Django so far I have not found it. <script type="text/javascript"> $("#id_people").focusout(function(){ cnpj_str = $("#id_people").val(); var er = /\^|~|\?|,|\/|\.|\-/g; cnpj_str = cnpj_str.replace(er, ""); $.ajax({ url: 'https://www.receitaws.com.br/v1/cnpj/'+$(cnpj_str), dataType: 'json', success: function(response){ if(reponse.status == "ERROR"){ alert(response.message + "\nError."); $("#post #nome").focus().select(); return false; } else { alert(response.message + "\nData OK"); } } }); }); -
Django rest_framework, disable authentication and permission in specific method
I have a class called UserViewSet : class UserViewSet(viewsets.ModelViewSet): queryset = UserData.objects.all() serializer_class = UserSerializer from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import TokenAuthentication permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) @action(methods=['post'], detail=False) def signup_user(self, request): request_data = request.query_params if len(request_data) == 0: return Response("Empty params !") Now i want to signup a new user and it will raise this error : { "detail": "Authentication credentials were not provided." } Its because of Authentication and Permission classes . So whats the correct way to disable this classes in signup function ? I used authentication_classes and permission_classes decorators but it has no effect on this function. -
django retrieving objects, empty values
I use Profile.objects.values('id', 'avatar') to retrieve objects from a table, but I want when value of avatar is empty to be set with media/profile.png, my model avatar = models.ImageField(upload_to='media', blank=True, default='media/profile.png') and return everything in json with JsonResponse(data, safe=False) [{"id": "1", "avatar": ""}, {"id": "2", "avatar": ""}, {"id": "3", "avatar": "media/profile.png"}, {"id": "4", "avatar": "media/art_xpr.png"}] and is used in javascript frontend, but the problem is that the avatar is empty in some cases . -
adding subquestions(take this as subqus1) from main questions only if he answer wrong in main question?
Adding subquestions(take this as subqus1) from main questions only if he answer wrong in main question? Add another subquestion(take this as subqus2) if he made the wrong answer in the subquestion(take this as subqus1)? questions = ["sudeer have 5 apples and raju have 6 apples.Totally how many apples they both have?",] sub_questions=["How much if 5 apples add with other 6 apples",] sub_questions1 =["you have 5 apples and your mother gave you other 6 apples.How many apples do you have with you?",] answer_choices = ["a)1\nb)2\nc)13\nd)11\n:",] correct_choices = [{"b", "2"},] answers = ["5 + 6 is 11",] def quiz(): score = 0 for question, choices, sub_question, correct_choice, answer in zip(questions, answer_choices, sub_questions, correct_choices, answers): print(question) user_answer = input(choices).lower() if user_answer in correct_choice: print("Correct") score += 1 elif: print("Incorrect:", sub_question) print(question) user_answer = input(choices).lower() if user_answer in correct_choice: print("Correct") score += 1 else: print("Incorrect", answer) print(score, "out of", len(questions), "that is", float(score / len(questions)) * 100, "%") if __name__ == "__main__": quiz() output: elif: SyntaxError: invalid syntax How can I do overcome from this error and let me know how to answer for the above questions from the front-end with the same format(main questions and subquestions)? Add another subquestion(take this as subqus2) if … -
Django filer - upload ajax file saved with added content: ---WebKitFormBoundary
I'm trying to use the ajax_upload (from https://github.com/divio/django-filer/blob/develop/filer/admin/clipboardadmin.py) function in a custom view with DRF: class FileUploadView(APIView): queryset = Joint.objects.all() serializer_class = serializers.Joint_Serializer parser_classes = (FileUploadParser, ) def post(self, request, ref, filename, format=None): data = { 'ref' : ref, 'file': request.FILES['file'], } serializer = serializers.Joint_Serializer(data=data) if serializer.is_valid(): ajax_upload(request) serializer.save() return JsonResponse({'OK':'Uplaoded'}) else: return JsonResponse(serializer.errors) this is the js of the ajax call function joint(id_row,prg){ var formData = new FormData(); formData.append("file" , $('#'+id_row)[0].files[0]); $.ajax({ url: url, type: 'POST', data: formData, cache: false, contentType: false, processData: false }).fail(function(e) { errori(e); }).done(function(result) { console.log(result); }); } The web page send the ajax call with the file, but I'm stuck in the ajax_upload at: b/python3.5/site-packages/filer/admin/clipboardadmin.py(134)ajax_upload() 133 {'error': 'failed to generate icons for file'}, --> 134 status=500, 135 ) ipdb> request.FILES {'file': <InMemoryUploadedFile: IMG-20170831-WA0000.jpg (multipart/form-data; boundary=----WebKitFormBoundaryevJbqjMCRBGzUJto)>} ipdb> FileSubClass <class 'filer.models.imagemodels.Image'> If I upload the same file in the admin it work fine. Just noted that the uploadedf files from this DRF view get an addiction of content at start and end of the saved file: ------WebKitFormBoundaryaHDQQnooZ3r2awkc Content-Disposition: form-data; name="file"; filename="IMG-7.jpg" Content-Type: image/jpeg ... ..image original content ... ------WebKitFormBoundaryaHDQQnooZ3r2awkc-- -
How to display the months list from a specific daterange in django?
Suppose I have a model: class Order(models.Model): created = model.DateTimeField(auto_now_add=True) total = models.IntegerField() and my query is: qs= Order.objects.filter(created__range=('2018,11,1','2019,11,1')) I want to see all the months present within the daterange given in the above query in my template... How to accomplish this in django? Any idea? -
AWS S3 presigned URL with metadata
I am trying to create presigned-url using boto3 below s3 = boto3.client( 's3', aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_ACCESS_SECRET, region_name=settings.AWS_SES_REGION_NAME, config=Config(signature_version='s3v4') ) metadata = { 'test':'testing' } presigned_url = s3.generate_presigned_url( ClientMethod='put_object', Params={ 'Bucket': settings.AWS_S3_BUCKET_NAME, 'Key': str(new_file.uuid), 'ContentDisposition': 'inline', 'Metadata': metadata }) So, after the URL is generated and I try to upload it to S3 using Ajax it gives 403 forbidden. If I remove Metadata and ContentDisposition while creating URL it gets uploaded successfully. Boto3 version: 1.9.33 Below is the doc that I referring to: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.generate_presigned_url -
python django rest framework. How to serialize foreign key UUID in some specific format?
I have two models A and B and both of them has UUID as primary keys. There is a foreign key in B related to A. class A(models.Model): id = models.UUIDField(primary_key=True, editable=False) desc = models.CharField(max_length=128, null=True) class B(models.Model): id = models.UUIDField(primary_key=True, editable=False) desc = models.CharField(max_length=128, null=True) for_key = models.ForeignKey(A, on_delete=models.SET_NULL, null=True) And here comes my serializer, class ASerializer(serializers.ModelSerializer): id = serializers.UUIDField(format='hex') class Meta: model = A fields = ('id', 'desc') class BSerializer(serializers.ModelSerializer): id = serializers.UUIDField(format='hex') class Meta: model = B fields = ('id', 'desc', 'for_key') As you can see, I have change the uuid(primary key) to hex format. But the for mat for the for_key is in the default format (hex_verbose). But how can I serialize the foreign key for_key in model B to hex format? -
Django - Reuploading und Updating CSV-File to Database
I would like to update my Django SQLite3 DB by reuploading a changed CSV-File. Here is my models.py class CSV_File8(models.Model): gebäudebereich = models.CharField(max_length=100) gebäudenr = models.CharField(max_length=100) ebene = models.CharField(max_length=100) raum = models.CharField(max_length=100) dose = models.CharField(max_length=100) switch_ip = models.CharField(max_length=100) switch_port = models.CharField(max_length=100) datum = models.CharField(max_length=100) akteur = models.CharField(max_length=100) class Meta: unique_together = (("gebäudebereich", "gebäudenr", "ebene", "raum", "dose"), ("switch_ip", "switch_port", "datum", "akteur")) my views.py class UploadFileForm(forms.Form): file = forms.FileField() def import_csv(request): if request.method == "POST": with open('C:/Users/admin/Desktop/djangoexcel/b.csv') as file: reader = csv.reader(file) id = 0 for row in reader: id += 1 # _, p = CSV_File8.objects.get_or_create(id = id, # gebäudebereich=row[0], gebäudenr=row[1], ebene=row[2], raum=row[3], dose=row[4], # switch_ip=row[5], switch_port=row[6], datum=row[7], akteur=row[8] # ) ds1 = CSV_File8.objects.filter(id = id, gebäudebereich=row[0], gebäudenr=row[1], ebene=row[2], raum=row[3], dose=row[4] ).values().exists() ds2 = CSV_File8.objects.filter(id = id, switch_ip=row[5], switch_port=row[6], datum=row[7], akteur=row[8] ).values().exists() if ds1 and id == id: pass if ds2 and id == id: pass if ds1 == False and id == id: _, ds1 = CSV_File8.objects.values().update(id = id, gebäudebereich=row[0], gebäudenr=row[1], ebene=row[2], raum=row[3], dose=row[4] ) if ds2 == False and id == id: _, ds2 = CSV_File8.objects.values().update(id = id, switch_ip=row[5], switch_port=row[6], datum=row[7], akteur=row[8] ) if ds1 and ds2 == False and id != id: _, ds2 = CSV_File8.objects.values().update(id=id, switch_ip=row[5], switch_port=row[6], … -
Django ckeditor - set width to 100%
I've got a simple django-ckeditor implementation with default settings set as CKEDITOR_CONFIGS = { 'default': { 'toolbar': [ ['Undo', 'Redo', '-', 'Bold', 'Italic', 'Underline', '-', 'Link', 'Unlink', 'Anchor', '-', 'Format', '-', 'SpellChecker', 'Scayt', '-', 'Maximize', '-', 'Language', ], ], 'height': '100%', 'width': '100%', 'toolbarCanCollapse': False, }, } Within my form I have {{ form.media }} {{ form.description }} I'm expecting the ckeditor field to cover 100% width but it covers 100% of the menu bar. How do I get it to cover the available width? Thanks -
Django REST Framework: 'BasePermissionMetaclass' object is not iterable
Python/Django n00b moving over from javascript. Trying to add an API endpoint using Django REST Framework which I'm hoping will ultimately be able to update a User with the body of a PATCH request, but for now I just want it to not throw a 500 error. I've added this to urlpatterns: url(r'update/$', views.UpdateView.as_view(), name="update_user"), And that should bring in this view: from django.contrib.auth.models import User from rest_framework.generics import UpdateAPIView from .serializers import UserSerializer class UpdateView(UpdateAPIView): queryset = User.objects.all() serializer_class = UserSerializer The UserSerializer looks like this: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'pk', 'status') Seem to be getting this every time I visit the route: TypeError at /api/update/ 'BasePermissionMetaclass' object is not iterable I have no idea what I'm doing - anyone seen this before? -
How to customize field names in Django admin change list only?
I have a model with many boolean flags. Some of them are displayed in admin change list and made editable by list_editable - this makes them appear as checkboxes. The problem is that this wastes a lot of horizontal space as field names are long (and I want to keep them descriptive for model change form). For regular fields I use custom properties and short_description to shorten the name. But in that case I have to render checkbox but I do not know how to make it properly. Or may be there is another hack to alter field name for change list only? -
Do Model Tree Transvaal
I'm using django-mptt django library in my django models to store hierarchical data in a database. I have built an accounting api whereby when defining accounts there is are root,parent and children accounts for instance a root account can be Assets then Cash Account will be categorized as an Asset account. My question was if using this library will cost me especially performance wise.If someone has used it please advice. Below is an illustration of how my model looks like: class Account(MPTTModel): """ Represents an account An account may have a parent, and may have zero or more children. Only root accounts can have an account_type, all child accounts are assumed to have the same account_type as their parent. An account's balance is calculated as the sum of all of the transaction Leg's referencing the account. Attributes: uuid (SmallUUID): UUID for account. Use to prevent leaking of IDs (if desired). name (str): Name of the account. Required. parent (Account|None): Parent account, none if root account code (str): Account code. Must combine with account codes of parent accounts to get fully qualified account code. account_type (str):Also identified as account classification - Type of account as defined by :attr:`Account.TYPES`. Can only be …