Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use variable in import statement
I am using some 3rd party JS file which uses an import statement inside the JS file itself. I am using Django, and that css file is in STATICFILES_DIRS, which I can access through {% static 'css/main.css' %}. This is the file being imported. In js this is being imported something like this import '../../css/main.css' I have declared a variable in index.html that holds this value index.html <script type="text/javascript"> const main_css = "{% static 'css/main.css' %}" </script> In my main.js file I am using this syntax @import `${main_css}` which doesn't work, the DOM doesn't change. Any tips? -
send multiple asynchronous http response for one request
there is a function which generates some result which is appended to an array in python, and the array is returned as a single http response. the computation is long. is there some way to send array values to front end for display as soon as they are generated in multiple http response. I tried using celery , but it puts tasks in a queue , not the results which can be returned to the front end. should i use web sockets? -
Access request in Boto3/Django storage class
I'm trying to set different S3 buckets to be used by different users of my Django app with Django Storages. A different bucket to write to and read from. I've set my DEFAULT_FILE_STORAGE to my custom class: from storages.backends.s3boto3 import S3Boto3Storage class CustomS3Storage(S3Boto3Storage): def __init__(self, *args, **kwargs): super(CustomS3Storage, self).__init__(*args, **kwargs) self.bucket_name = 'app-files' I would like to access the request from one of my class based views, but can't seem to find a way to do that. The logic would then be: self.bucket_name = request.user.profile.bucket How can I do that? Should I edit this in the class-based views? -
Django Check running port View
i am new on Django My problem is when i want to check if the port are running or not just print it in the index.html page Nothing Show up this is my code View.py import socket def port(request): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex(('127.0.0.1',8000)) if result == 0: msg = 'Port is open' context = {'msg': msg} return render(request, 'CharsAccount.html',context) else: msg ='Port is not open' context = {'msg': msg} return render(request, 'CharsAccount.html',context) Html file <h1>PORT{{msg}}</h1> No thing Show up sorry for my bad english -
python: Error: dictionary changed size during iteration @ when trying to iterate over django request object
In python in a dictionary if key is byte string then json.dumps will throw error, So I am trying to convert recursively all the keys as string before passing them to json.dumps. Note: json.dumps converts the value to str using default function but not keys The following is my function which will check for any byte string keys and convert them to string: def keys_string(d): rval = {} if not isinstance(d, dict): if isinstance(d,(tuple,list,set)): v = [keys_string(x) for x in d] return v else: return d for k,v in d.items(): if isinstance(k,bytes): k = k.decode() if isinstance(v,dict): v = keys_string(v) elif isinstance(v,(tuple,list,set)): v = [keys_string(x) for x in v] rval[k] = v return rval I am debugging some code in django I want to check the request object at certain point of my code So i have request_dir = dir(request) then convert any byte keys to string using keys_string (Else json dumps will throw error) request_dir_keys_stringed = keys_string(request_dir) Then finally json.dumps(request_dir_keys_stringed, indent=4, sort_keys=True, default=str) When i am trying to do request_dir_keys_stringed = keys_string(request_dir) it says in keys_string for k,v in d.items(): RuntimeError: dictionary changed size during iteration I tried for request.session object it does not throw such error. But some … -
How do I pass the users model as the ForeignKey value while saving a ModelForm in Django?
The models file: from django.db import models from django.conf import settings class Book(models.Model): rel_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="Posted By") title = models.CharField(max_length=256, verbose_name="Title") description = models.TextField(verbose_name="Description") price = models.IntegerField(verbose_name="Price") state = models.CharField(max_length=256, verbose_name="State") city = models.CharField(max_length=256, verbose_name="City") neighbourhood = models.CharField(max_length=256, verbose_name="Neighbourhood") phone = models.IntegerField(verbose_name="Phone Number") def __str__(self): return self.title + f" ({self.rel_user.username})" The forms file: from django.forms import ModelForm from Books.models import Book class BookForm(ModelForm): class Meta: model = Book fields = ['title', 'description', 'price', 'state', 'city', 'neighbourhood', 'phone'] The views file: from django.shortcuts import render, redirect from Books.forms import BookForm from django.contrib import messages def sell(request): if request.method == "GET": form = BookForm() else: form = BookForm(request.POST, ) if form.is_valid(): form.save() messages.success("Successfully added!") return redirect('sell') else: messages.error("Please fill in all the fields.") return render(request, 'Books/sell.html', {"form": form}) Every time a user submits the form, I want the ForeignKey's value to be filled with that users model. How do I do this? So suppose user "John" has filled the form. When he clicks submit, the details he enters + his user model should go into the database for that entry. -
request.POST.get('encResp') returns None on PROD env (linux, Apache, MySQL, Python, Django), while the same work on local
request.POST.get('encResp') returns None on PROD env (linux, Apache, MySQL, Python, Django), while the same statement returns data as expected on my local env (Window 8, MySql, Python, Django) Usecase Breif: Payment Gateway (PG) Integration: Testing Phase: Code checked into PROD, with PG test urls still. I submit to Payment URL ... that returns Response Data to my callback URL. Control reaching to my callback url, but the said request.POST.get('encResp') is returning 'None' NOTE: I am sending some data long with call url as query params .. and those are successfully received via the request.GET.get('qs') call back url: (local works) http://localhost:8000/payment/done/?qs=5b69961d5c3c1d06fc21c324804d8bb0f229798f20ebc4f89bc9b13bc5618cb3 call back url: (prod fails) https://xxxxxxxxx.org.in/payment/done/?qs=df86a2638205e3b8989336da02cedf33 Not sure whats missing on PROD ... only difference i see is Apache2 webserver in between the call back which i dont have in local env Appreciate some pointers/suggestions -
Problem with aws s3, django projrct storage files?
I'm trying to use AWS S3 for my project files and uploads, the problem is that the data are not coming because of the wrong region (EU instead of eu-central-1) Good image link from the bucket: https://card-clash-files.s3.eu-central-1.amazonaws.com/profile_pictures/AKSQ3821.JPG Link in my website: https://card-clash-files.s3.eu.amazonaws.com/profile_pictures/IMG_1178.JPG?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAWK5ABWGNAXQY5WED%2F20200109%2FEU%2Fs3%2Faws4_request&X-Amz-Date=20200109T104019Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=89c5d5bba335d4cd6dca8f9db0277ee557bf534aa012e3607b8010ae8ee6432d -
Live validation message in django?
I was making a register page in my django project and i wanted to display a error message until conditions like username/email is taken are false I used the messages.info to store the messages that I later output in my html page but the messages don't load or reset until I refresh the page I wrote this code in the views.py file: def register(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] if password == password2: if User.objects.filter(username=username).exists(): messages.info(request,'Username Taken') return redirect('') elif User.objects.filter(email=email).exists(): messages.info(request,'Email Taken') return redirect('') else: user = User.objects.create_user(username= username,password=password2,email=email) user.save() else: messages.info(request,'Passwords Dont Match') return redirect('/')`enter code here else:`enter code here` return render(request,'register.html') -
IntelliJ django unittests 'Apps aren't loaded'
I have a few unittests in my project, these can be run by python manage.py test which works fine. Now I want to test some test-cases alone with the IntelliJ built-in tester (where each test a this little green triangle). If I run a specific test through IntelliJ I get: File "/Users/user1/ProgProjects/active/law-orga/backend/venv/lib/python3.6/site-packages/django/apps/registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Process finished with exit code 1 Empty suite Empty suite My environment variables contain PYTHONUNBUFFERED=1;DJANGO_SETTINGS_MODULE=backend.settings; (backend is the name of the app). I tried to add django.setup() to my settings.py file, then the tests work but they use the local database, not a dedicated test database which gets built and destroyed every time. Additionally the teardown still works, so my local database just gets whipped at the end. I use the most recent version of IntelliJ Ultimate. -
AJAX fails when it is moved to another js file in Django project
I have a code in index.html file: <script> $.ajax({ type: 'GET', url: '{% url "myProject:load" %}', data: {val: document.getElementById('val').value, sections: secCols}, success:function(json){}, error : function(xhr,errmsg,err) { alert("ajax error: load") } ... </script> load is a function within views.py: def load(request): ... I move this piece of code into a js file in another folder. It produces an error after I move it. Can you say how to fix it? -
How to update an existing record in Django?
I am trying to update an existing record in Django but whenever I POST request with postman I get the following. It says that it already exists. So i tried to assign task_1 = Task.objects.get(pk=task_id) task_1 = ser But I get an error that i cant assign it My current code: class TaskView(APIView): permission_classes = (IsAuthenticated,) def post(self, request, task_id): task_obj = find_task(request.auth, task_id) if task_obj: task = task_obj.data my_data = json.loads(request.body) keys = list(my_data.keys()) keys.remove('photo_path') for key in keys: task[key] = my_data[key] ser = TaskSerializer(data=task) ser.is_valid(raise_exception=True) ser.save() return Response(ser.data) else: return Response(status=status.HTTP_404_NOT_FOUND) # Returns the task only if its assigned to current user def find_task(token, task_id): u_id = Token.objects.get(key=token).user_id assign_to = AssignTo.objects.filter(task_id=task_id, user_id=u_id) if len(assign_to) > 0: task = Task.objects.get(pk=task_id) serializer = TaskSerializer(task) return serializer else: return False So how do I update this task? -
Django: Trying to understand the syntax of accessing request.session[SESSION_KEY]
I am trying to undestand the syntax of request.session[SESSION_KEY] in django/contrib/auth/__init__.py The following are the details: DJANGO FILENAME: django/contrib/auth/__init__.py SESSION_KEY = '_auth_user_id' def _get_user_session_key(request): return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY]) When i was debugging i check the the properties of request.session using dir(request.session) and later using json.dumps() I found the following properties: "_SessionBase__not_given": "<object object at 0x7fdec4d70160>", "_SessionBase__session_key": "soiceej5uzukby0oef92woo0n47jiph4", "__dict__": { "_SessionBase__session_key": "soiceej5uzukby0oef92woo0n47jiph4", "_session_cache": { "_auth_user_backend": "django.contrib.auth.backends.ModelBackend", "_auth_user_hash": "6b39441cc03a5d82c9fb9b8782c7b231b6d55924", "_auth_user_id": "6", "jwt_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InNpbWhhcnVwYS5ybnNAZ21haWwuY29tIiwiT1RQIjoiNTQ1ODI2IiwiY3JlYXRpb25fdGltZSI6IjIwMjAtMDEtMDlUMDU6MzM6MjMuNDAwMTc0KzAwOjAwIn0.SYDED2D5KqhZwboxGmTj9TtdSyIoGQaHBaCGRtms4uo" }, "accessed": true, "model": "<class 'django.contrib.sessions.models.Session'>", "modified": false, "serializer": "<class 'django.core.signing.JSONSerializer'>" }, "__doc__": "\n Implement database session store.\n ", "__module__": "django.contrib.sessions.backends.db", "__weakref__": null, "_session": { "_auth_user_backend": "django.contrib.auth.backends.ModelBackend", "_auth_user_hash": "6b39441cc03a5d82c9fb9b8782c7b231b6d55924", "_auth_user_id": "6", "jwt_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InNpbWhhcnVwYS5ybnNAZ21haWwuY29tIiwiT1RQIjoiNTQ1ODI2IiwiY3JlYXRpb25fdGltZSI6IjIwMjAtMDEtMDlUMDU6MzM6MjMuNDAwMTc0KzAwOjAwIn0.SYDED2D5KqhZwboxGmTj9TtdSyIoGQaHBaCGRtms4uo" }, "_session_cache": { "_auth_user_backend": "django.contrib.auth.backends.ModelBackend", "_auth_user_hash": "6b39441cc03a5d82c9fb9b8782c7b231b6d55924", "_auth_user_id": "6", "jwt_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InNpbWhhcnVwYS5ybnNAZ21haWwuY29tIiwiT1RQIjoiNTQ1ODI2IiwiY3JlYXRpb25fdGltZSI6IjIwMjAtMDEtMDlUMDU6MzM6MjMuNDAwMTc0KzAwOjAwIn0.SYDED2D5KqhZwboxGmTj9TtdSyIoGQaHBaCGRtms4uo" }, "_session_key": "soiceej5uzukby0oef92woo0n47jiph4", "TEST_COOKIE_NAME": "testcookie", "TEST_COOKIE_VALUE": "worked", "accessed": true, "modified": false, "session_key": "soiceej5uzukby0oef92woo0n47jiph4" Then how does request.session['_auth_user_id'] work As per my understanding from its properties it should be request.session._session_cache['_auth_user_id'] OR request.session.__dict__['_session_cache']['_auth_user_id'] -
Extract data from my Django API in my database using id
I have build an api with django rest framework when I call it with url (http://127.0.0.1:8000/api/) i get follwing data: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "name": "Tony Stark", "age": 45, "gender": "Male", "address": "10880 Malibu Point, Florida", "email": "starks@industry.com", "image": "/media/media/ironman.jpg" }, { "id": 2, "name": "Wanda", "age": 32, "gender": "female", "address": "Goregaon east, 12009", "email": "wandamaximaoff@gmail.com", "image": "/media/media/scarlet.jfif" }, { "id": 3, "name": "Shaswat", "age": 22, "gender": "male", "address": "Naigaon east,vasai road, Victoria co. hsg.so, 401208", "email": "kumarshaswat9@gmail.com", "image": "/media/media/Untitled-1.jpg" }, { "id": 4, "name": "Naruto", "age": 21, "gender": "male", "address": "mira road east, konaha apt, 9008", "email": "naruto@yahoo.in", "image": "/media/media/cropped-1920-1080-47438.png" } ] My question is how do I extract a single set from this entire data set I have app named clientside in which I have views.py #This is what I tried links(1. https://www.django-rest-framework.org/topics/api-clients/)# from django.shortcuts import render import coreapi import json from django.views import generic def home(request): client = coreapi.Client() response = client.get('http://127.0.0.1:8000/api') #data = json.loads(response) data = json.dumps(response) name = data.get("name") age = data.get("age") gender = data.get("gender") user = UserReceived.objects.create(id=id, name = name, age= age, gender = gender) user.save() # return render(request, 'books.html',{'name': data['name'],'gender': data['gender']}) … -
saving different value in database
I am creating a app using django rest-framework to record mensuration date.I have to put a validation to date fields like if one date is already entered in database the app should avoid to enter same date which is already exist in database. Need help to do that -
django-versatileimagefield issues: 'No matching distribution found for python-magic-bin' when deploying to Google App Engine Flex
Since upgrading to django-versatileimagefield==2.0, I just can't get it to play nicely with Google App Engine. Using it as is comes up with the error that others have reported: ImportError: failed to find libmagic. Check your installation I've read similar problems that mention adding python-magic-bin==0.4.14 to the requirements. That seems to rectify the problem locally. When I deploy to Google App Engine, though, it fails when when trying to install python-magic-bin with: Could not find a version that satisfies the requirement python-magic-bin==0.4.14 No matching distribution found for python-magic-bin==0.4.14 I am using the App Engine Flexible environment with Python 3.7.2. I've tried numerous different ways of installing the required packages and I just can't get it to work. -
How to call the function in Django on button click?
I'm making a trading bot in Django and here I want to call a function on a button click. Is this possible? if yes then how to do it? views.py def trade(request): def main(self): message = "hello I am working" return message return render(request, 'trade.html') Please help me on how to call the function "main" on button click. I didn't try anything yet. -
How to append the serializer in django rest framework
class EmployeeListSerializer(serializers.ModelSerializer): """ Employee List view get """ user_profile = UserProfileSerializer() employer_info = serializers.SerializerMethodField() @staticmethod def get_employer_info(instance): """ To get employer info :return: """ return UserEmployeeCreatedBySerializer(instance.employer_info()).data class Meta(object): """ User meta class. """ model = User fields = ('id', 'first_name', 'last_name', 'full_name', 'email', 'phone', 'user_profile', 'employer_info') This is my serializer { { "page_data": null, "data": { "count": 11, "next": "", "previous": null, "results": [ { "id": 14, "first_name": "Robin", "last_name": "chauhan", "full_name": "Robin Chauhan", "email": "robinchauhan@gmail.com", "phone": "8750795058", "user_profile": { "address": "avengers building", "country": "usa", "state": "washington", "city": "manhatten", "zip_code": "string", "latitude": 0, "longitude": 0, "company_name": "string", "employee_size": 34 }, "employer_info": { "is_active": false, "created_by": { "email": "", "first_name": "", "last_name": "" } } This is my api result { { "page_data": null, "data": { "count": 11, "next": "", "employer_info": { "is_active": false, "created_by": { "email": "", "first_name": "", "last_name": "" } "previous": null, "results": [ { "id": 14, "first_name": "Robin", "last_name": "chauhan", "full_name": "Robin Chauhan", "email": "robinchauhan@gmail.com", "phone": "8750795058", "user_profile": { "address": "avengers building", "country": "usa", "state": "washington", "city": "manhatten", "zip_code": "string", "latitude": 0, "longitude": 0, "company_name": "string", "employee_size": 34 } } I want it like this -
Not updating profile picture in Django
This is a bit of repetition on a previous question I asked. However, I believe I made substantial enough changes to the code to warrant asking a new question as I am getting a new error message. This is my code in views.py(teachers.py): # edit mentor profile def edit_user(request): user = request.user # form = MentorProfileForm(instance=user) if request.method == 'POST': form = UserForm(request.POST, instance=user) mentorform = MentorProfileForm(request.POST, request.FILES, instance=user) if form.is_valid() and mentorform.is_valid(): form.save() mentorform.save() messages.success(request, ('Your profile was successfully updated!')) return HttpResponseRedirect('%s' % (reverse('profile'))) else: messages.error(request, ('Please correct the error below.')) else: form = UserForm(request.POST, instance=user) mentorform = MentorProfileForm(request.POST, request.FILES, instance=user) return render(request, 'classroom/teachers/app-instructor-profile.html', {'form': form, 'mentor_form': mentorform}) forms.py #basic form class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name','last_name','email') # edit mentor profile class MentorProfileForm(forms.ModelForm): class Meta: model = Mentor fields = ('photo',) models.py: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) ... class Mentor(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) linkedin = models.URLField(max_length=200,null=True,blank=True) photo = models.ImageField(null=True,blank=True,upload_to='media') def __str__(self): return "Profile of user {}".format(self.user.username) @receiver(post_save,sender=User) def create_or_update(sender, instance,created, **kwargs): if created: post_save.connect(create_or_update, sender=User) the html form: <form id="edit-mentor-profile" class="form-horizontal" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="photo" class="col-sm-2 control-label">Avatar</label> <div class="col-md-6"> <div class="media v-middle"> <div class="media-left"> <div class="icon-block width-100 … -
Django - Bulk operation on various model instances, in a table where cells are already wrapped up in a form
Apologies for this very generic question but is there a clean way to do basic operations (delete/update, etc..) on several model instance, at once, where these models are displayed in a table where they are populating the headers of the columns only but all cells are already wrapped in forms? I initially thought of wrapping the entire table in a form but nested forms won't work. Table: model1 / cell a / cell b / cell c model2 / cell d / cell e / cell f model3 / cell g / cell h / cell I In the table above, I am trying to bulk delete models listed, everytime the checkbox next to them is ticked -
AWS CodePipeline - Deployment to Elastic Beanstalk has taken 18 hours. How do I cancel it?
I have a codepipeline that feeds from GitHub into Elastic Beanstalk. It has currently been deploying for 18 hours and hasn't stopped. Admittedly, I probably made a mistake with removing an App from a Django project incorrectly, but how do I cancel the Elastic Beanstalk Deployment? To be honest, I'm not even sure if it is deploying correctly because the EB hasn't updated when I look at it inside Code Pipeline but it is in progress when I look at it outside and the blue wheel is spinning (see pictures). Can I just remove the database and then redeploy the Django project to re-initiate everything from scratch ? This isn't a production system, so it isn't critical. Thanks for your help. -
How to get Current Date and Time in Django [duplicate]
This question already has an answer here: Automatic creation date for Django model form objects? 2 answers Am not able to figure out what mistake am doing created_date = models.IntegerField(default=datetime.today.strftime('%Y-%m-%d')) # created_date = models.DateTimeField(auto_now_add=True, default=timezone.now()) created_time = models.IntegerField(default=datetime.now.strftime('%H:%M:%S')) # created_time = models.TimeField(auto_now=True, default=timezone.now()) road_name = models.CharField(max_length = 100, default = 'NULL') -
Matching Query Doesn't exist DJANGO?
its always returning matching query doesn't exist. it means the model doesn't exist. but it's existing in the database. should I check it at another place or why this is not existing? as much I know Django migration, migrating will create and delete models every time. but why this UserFeatureSet isn't created. UserFeatreSet is the name of my model. Request - can anyone please explain the working of Django migrations. UserFeatureSet matching query does not exist.``` -
Add Binary data into django rest framework API
model.py class TblSnapshot(models.Model): url = models.CharField(max_length=500) snapshot = models.BinaryField() I want to add Binary Data in API, but it's generating error TypeError at /api __str__ returned non-string (type memoryview) -
How to paginate item
How do i paginate item in category. I have a category name men_clothing_shirt, i want to paginate all item on the template. The problem is when i change the paginator to 1, it displayed all item on one page instead of just displaying only one item on one page. When i click on the next button it takes me to page2 but all items still display there. The paginator do not paginate the item accordingly to the page. See uploaded images. def men_shirt(request): queryset_list = Category.objects.filter(name='man_clothing_shirt') paginator = Paginator(queryset_list, 1) page = request.GET.get('page') try: queryset = paginator.page(page) except PageNotAnInteger: queryset = paginator.page(1) except EmptyPage: queryset = paginator.page(paginator.num_pages) context = { 'menshirtpaginator': queryset, } return render(request,'men_shirt.html', context)