Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use websockets client/server between two Celery tasks?
I use Celery and Redis in my Django application to handle tasks and one of them is to subscribe to a websocket stream to receive financial data in an async loop. Of course others Celery tasks need these informations and I'm trying to figure out how to transmit the data to them. So far I tested writting the stream every x seconds into the database, works but consummes CPU. Not really efficient and cannot be real-time. Another solution could be to update a dictionary when fresh data arrive but unfortunnatly Celery tasks are executed in seprate processes so that global variable from one task isn't accessible in another task. After some research I came to the conclusion that best solution is to use the websockets library and I'm trying to implement this example of a websocket client/server. The idea is to start the ws server in the same task that receive the stream of financial data so it can transmit the data to another 'client' task. To do so I declared a global variable data which contain the stream as it arrives, and it's this variable I would like to transmit to the client in the gretting message. The server … -
Creating applications with django
I made 'Pollsapp' through the pycharm and django, but I can't see it. However, it can be checked on the admin site. When I search with "127.0.0.1:8000/Pollsapp/", it says "No Question". I registered the app(Pollsapp) on settings.py. And page not found (404) appears when I search http://127.0.0.1:8000/. Is this the problem? Only admin site operates normally. What do you think is the problem? I didn't understand this system well, so please let me know if you need any more information. -
Amazon S3 buckets, limit the number of request per day, limit of size
currently developping a "social network"-like website, I plan to use an Amazon S3 bucket to store users'profile pictures. Does anyone know whether there is an easy way to set : the maximum number of requests per day a bucket can accept the maximum size that the bucket can reach the maximum size a given picture must not exceed to be accepted My fear being that a given user would upload such a big picture (or such a big number of pictures, or create such a high number of profiles) that my amazon S3 bill would skyrocket... (I know that some 'a posteriori' alerts can be set, but I'm looking for a solution that would prevent this situation..) Any help greatly appreciated ! -
RuntimeError: populate() isn't reentrant import loop
I have my models.py file import an external function which then writes to a specific model. I think this is some sort of import loop but I'm not sure. This is a partial traceback File "path/Directory/Package/models.py", line 19, in <module> from externalFunction import myFunction File "path/Directory/externalFunction.py", line 9, in <module> django.setup() File "/path/anaconda3/envs/myEnv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/path/anaconda3/envs/Brew/lib/python3.6/site-packages/django/apps/registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant File structure >Directory manage.py externalFunction.py >Package models.py >Package_api wsgi.py models.py from django.db import models import sys sys.path.append("..") from externalFunction import myFunction class Job(models.Model): name = models.CharField( max_length=30, default="name") externalFunction.py import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Package_api.settings') django.setup() from Package.models import Job def myFunction(): some stuff I've tried removing django.setup() from externalFunction.py but then it cannot import Job from the models. -
Data is not being saved as Encrypted data django
till now I tried more then 6 plugins and quite frustrate now. Now using this one cryprtography everything is fine and done accordingly but when I save data in model manager like this def create_user(self, email, password, **extra_fields): user = self.model(email=email, **extra_fields) user.test_field = 'tousif.noor@oc.com' user.save(using=self._db) return user it saving data normally not encrypted My model is like class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) test_field = encrypt(models.CharField(max_length=100)) objects = UserManager() -
How to change a boolean of Active True to false after a time frame
I am trying to set a parameter for a boolean from True to false after a time frame. For my limited knowledge in Python and Django, I am trying to learn the concept and the logic so that I can apply it in different other places in the project. here is the Models.py class Coupon(models.Model): code = models.CharField(max_length=15, unique=True) valid_from = models.DateTimeField(blank=True, null=True) valid_to = models.DateTimeField(blank=True, null=True) active = models.BooleanField(default=True) How do set that when the time frame is after valid_to the Active=status becomes False here is the views.py class AddCouponView(View): def post(self, *args, **kwargs): now = timezone.now() form = CouponForm(self.request.POST or None) if form.is_valid(): try: code = form.cleaned_data.get('code') order = Order.objects.get( user=self.request.user, ordered=False) coupon = Coupon.objects.filter(code__iexact=code, valid_from__lte=now, valid_to__gte=now).exclude( order__user=self.request.user, max_value__lte=F('used')).first() if not coupon: messages.error(self.request, 'You can\'t use same coupon again, or coupon does not exist') return redirect('core:checkout') else: try: coupon.used += 1 coupon.save() order.coupon = coupon order.save() messages.success(self.request, "Successfully added coupon") except: messages.info(self.request, "Max level exceeded for coupon") return redirect('core:checkout') except ObjectDoesNotExist: messages.info(self.request, "You do not have an active order") return redirect('core:checkout') -
Djoser password reset implementation
I am using djosers for my authentication on django backend which eventually i'll be connecting to flutter frontend and i am having trouble implementing the password reset functionality... from what i have understood, first i need to hit the /users/reset_password/ with email body which will eventually give me the token of authentication which will be used further on confirm reset but the first thing i dont understand is PASSWORD_RESET_CONFIRM_URL field in the settings, like it needs a front end link with uid and token placeholders but what is this token field and what is this PASSWORD_RESET_CONFIRM_URL but i managed to look over a stack overflow question and filled it but now when i hit /users/reset_password/ i get this error [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions settings: DJOSER = { 'PASSWORD_RESET_CONFIRM_URL':'reset/password/reset/confirm/{uid}/{token}', 'LOGIN_FIELD' : 'email', 'USER_CREATE_PASSWORD_RETYPE' : True, 'SERIALIZERS': { 'user_create': 'auth_app.serializers.UseriCreateSerializer', 'user': 'auth_app.serializers.UserCreateSerializer', } } urls.py: urlpatterns = [ path('',home,name='home'), path('addInForum/',addInForum,name='addInForum'), path('addInDiscussion/',addInDiscussion,name='addInDiscussion'), path('<str:forum_id>/getDiscussion/',getDiscussion,name='getDiscussion'), path('getDate/',getDate,name='getDate'), path('reset/password/reset/confirm/<str:uid>/<str:token>/',PasswordResetView,name='PasswordResetView'), # url(r'^reset/password/reset/confirm/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/$', PasswordResetView.as_view(),), ] views.py @api_view(['GET']) def PasswordResetView(request,uid,token): post_data = {'uid': uid, 'token': token} return Response(post_data) -
Django fails to save recorda to database
Please am currently stuck at a juction trying to send data to the database. I created my HTML form fromsceatch and didn't make use of Django built in crispy_form. Whenever I hit the submit button it saves everything fields as'None'. What I could observed from my method is that, it keeps returning a GET request instead of a POST request. Please how can I solve that. Have been stuck on this thing for over a week, I'll really appreciate if I get a solution here. Thanks. -
Django filtering error: annotate + distinct not implemented
I'm using Django 2.2 and I need to group a query set by month and count the number of rows Input: Id | Value | Date 1 | Example value 1 | 2020-02-10 2 | Example value 2 | 2020-02-17 3 | Example value 3 | 2020-03-21 4 | Example value 4 | 2020-04-15 Expected output Month | Count 2020-02 | 2 2020-03 | 1 2020-04 | 1 I'm using an initial filtering like this. details = Process.objects.filter(started_at__gte=start_date, finished_at__lte=end_date).order_by('-serial_number').distinct('serial_number') #Some code using all details #Filtering After that I need to do the group by and count. summary = (details .annotate(m=Month('started_at')) .values('m') .annotate(total=Count('id')) .order_by('id').distinct('m','id')) But when I execute it I got the following error: NotImplementedError: annotate() + distinct(fields) is not implemented. Month class definition: class Month(F): function = 'EXTRACT' template = '%(function)s(MONTH from %(expressions)s)' output_field = models.IntegerField() I'm trying to do something like this. Django: Query Group By Month -
Syntax to append variable to {% url 'app_name:viewname' %}
How do I append a variable to a url name in a template, for eg.: {% for table in tables %} <a href="{% url 'menu:menu_view' %}"> <button class="button table{{table.pk}}">Table {{table.pk}}</button> </a> {% endfor %} With table.pk as a counter (passed in from view function), I would like to tag it to menu:menu_view so that I could have menu:menu_view1,menu:menu_view2, etc. And then I could name my urlpatterns as following: path('<int:table.pk/', views.menu_view, name='menu_view' + str(table.pk)), -
How to write Ajax logic in view for a reply comment form?
I created a comment thread view wherein it has comment and its relevant replies and reply form. This form works fine, but I only couldn't Ajaxify it. here is the form. <form action="." method='post' class="reply-form"> {% csrf_token %} <div class="input-container"> <label for="comment">Comment</label> <input type="hidden" name="content_type" value="blogs | blog" id="id_content_type"> <input type="hidden" name="object_id" value="1" id="id_object_id"> <input type="hidden" name="parent_id" value={{ comment.id }}> <textarea name="body" id="comment" class="input-textarea" rows="2" ></textarea> </div> <input type="submit" value="Reply" class="button" /> </form> This is what I tried but didn't work, I sent this Ajax form when form is submitted. $(document).on("submit", ".reply-form", function (e) { e.preventDefault(); $.ajax({ type: "POST", url: $(this).attr("action"), data: $(this).serialize(), dataType: "json", success: function (response) { $(".form-container").html(response["form"]); $(".reply-btn").click(function (event) { event.preventDefault(); $(this).parent().next(".comments").fadeToggle(); }); }, error: function (rs, e) { console.log(rs.responseText); }, }); }); and in turn, this request calls the following view def comment_thread(request, pk): obj = get_object_or_404(Comment, pk=pk) initial_data = { 'content_type': obj.content_type, 'object_id': obj.object_id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): content_type = ContentType.objects.get_for_model( obj.content_object.__class__) object_id = form.cleaned_data.get('object_id') body = form.cleaned_data.get('body') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_queryset = Comment.objects.filter(id=parent_id) if parent_queryset.exists() and parent_queryset.count() == 1: parent_obj = parent_queryset.first() comment, created = Comment.objects.get_or_create( user=request.user, content_type=content_type, object_id=object_id, … -
Efficient way to query objects based on their coordinates in Django
I am tying to retrieve several objects and make a separate list for each based on their start location. For example, we have a query of 6 objects, and all of them have different start_loc. I want to make a list that have objects with their start_loc within 30 meters from each other. So, the list would look like [[obj1, obj2, obj3], [obj4, obj5]] My code is as follows: hikes = Hikes.objects.all().order_by('start_loc') eff_hikes = _eff_hikes(hikes) def _eff_hikes(hikes): ref_coords = [] for i in range(len(hikes) - 1): this_hike = hikes[i].start_loc next_hike = hikes[i+1].start_loc dis = D(m=this_hike.distance(next_hike)) if this_hike != next_hike and dis > D(m=30): ref_coords.append() = hikes[:i+1] # some more code return ref_coords This does not help and makes my code complicated. Is there a better solution to this problem? -
Creating object in django models
ck.imgur.com/ZK6tB.png Hi everyone. I've just began django with a tutorial, and created my models, objects in cmd. When i create an obj, it requires the first attribute title to be a num, otherwise an error. But i have Charfield in title, so why that happens? If need, i'll add screens of other apps -
Type Error: Format Requires Mapping in Django
In the python shell I have been trying make the following query: from fixtures.models import Summary Summary.objects.get(team='Liverpool') But I get the following error: TypeError: format requires a mapping But when I try to get the team from the first object it works: Summary.objects.first().team >>>'Liverpool' Any idea on how to solve this problem? Thanks -
DRF How to test file uploads?
I have a simple model, a serializer and a view. I want to upload a file over the view but no method I found worked. Here's my code: def test_api_post(self): lesson = self.Create_lesson() file = SimpleUploadedFile( "file.txt", "".join(random.choices(string.ascii_letters + string.digits, k=1024 * 5)).encode(), "text/plain" ) response = self.client.post( "/api/submission/", { "lesson": lesson.id, "file": file }, format="multipart" ) self.assertStatusOk(response.status_code) # Error I tried it using with open() as file and I also tried using path.read_bytes(). Nothing worked. How can I test binary file uploading with django-rest-framework's test client? doesn't work, https://gist.github.com/guillaumepiot/817a70706587da3bd862835c59ef584e doesn't work and how to unit test file upload in django also doesn't work. -
Get selected value from dropdown menu django displayed with for loop
I am building an upload app using Django where the user uploads a file, I display for the user the headers of the file, and the user has to map the headers of the file to my Django model attributes. I want to have access in the views.display_success_page function to the selection of the user in the drop-down menu mapping.html (approximate html) {% for header in file_headers %} <td>{{ header }}</td> {% for attribute in model_attributes %} <li> <a class="dropdown-item" id="attribute">{{ attribute }}</a> </li> {% endfor %} {% endfor %} <button>Submit</button> views.py def display_success_page(request): if request.method == "POST": selected_value = request.POST.get('attributes') return render(request, 'upload_success.html') I do not manage to find in request dictionary the 'attributes' id. I tried to build something with forms, but I don't know where to put the form. This -> Django:get field values using views.py from html form was not helpful because each user_selection is not unique, it does not have its own name. -
Django - Fetching entities whose many-to-many relationship contains all terms collectively
I am trying to create a Recipe API in django, I have tried to implement a many-to-many relationship between recipes and ingredients like so: models.py class Ingredient(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Recipe(models.Model): title = models.CharField(max_length=50) description = models.TextField(blank=True) ingredients = models.ManyToManyField(Ingredient) How can I return recipes who's ingredients are a subset of a list of ingredients provided? e.g a recipe that contained only milk, sugar and eggs should be returned when queried with (milk, chocolate, ham, egg, sugar, cheese) along with other recipes who's ingredients are a subset of the list. -
encode base64 image upload is restricted by modsecurity
I started to face a problem of uploading image using encode base64 when I enabled mod-security I tried to change from #SecRequestBodyLimit 13107200 #SecRequestBodyNoFilesLimit 131072 to SecRequestBodyLimit 13107200 SecRequestBodyNoFilesLimit 13107200 the 413 error (HTTP Error: 413 Request Entity Too Large) stopped but still I cannot upload the image. -
Django Private Files - How to hide them
I am trying to add Firebase to Django, which works perfectly. However, I have to save a credentials file with my private keys and such. Currently I just have it saved in the project directory, however, how do I hide this file when uploading to Git for deploying onto something like Heroku? Basically, my question is how do I hide such files. Does it have something to do with Environment variables? -
Customizable Search Query REST API provided via Backend for Frontend [django.python]
I am currently working on some backend API's to service the frontend and return information from a MySQL database. I have http GET methods that can return a JSON object (queryset) based on a primary key(s) passed in the URL by the frontend team. The problem is, the search criteria are numerous (supplier name, price range, labels, service region, delivers or not.. etc). And I have no way of telling which of these filters the front end user will use to filter.. And it seems very redundant and wasteful (and difficult to maintain) to create a GET handler for each and every possible combination of used/unused search filters and return the desired JSON object(s) from the database. My question is - can the frontend pass a JSON object containing the search criteria along with the GET request? If not, what is the "standard" technique used for such scenarios.. I tried google but I have no idea what to look for. Stack Overflow is always a last-option resort since most people here are usually obnoxious and extremely unwelcoming of beginners. I hope this time changes my mind. -
Serializer.data not evaluating queryset in tests
I have such serializer class ActResultSerializer(serializers.Serializer): actions = serializers.SerializerMethodField() def get_actions(self, obj): return Actions.objects.filter(type='solution').values_list('code', flat=True) Here is my test case def test_return_to_provider(self): response = self.client.get('/acts/') self.assertEqual(response.status_code, 200) queryset = Act.objects.filter(deleted=False) self.assertEqual( len(response.data), queryset.count() ) self.assertEqual(response.data, ActResultSerializer(queryset, many=True).data) The problem is, that last assertEqual fails, because serializer data returns ('actions', <QuerySet []>). How can I evaluate that QuerySet to compare response and serializer datas? -
using custom Profile model field as keyword in url to give multiple people access to one account in django app
Here is the scenario I am working on: I have django app that creates records which I call sessions: blog.models.py class Session(models.Model): uid = models.CharField(max_length=50, blank=True) cid = models.CharField(max_length=50, blank=True) action_type = models.CharField(max_length=50, blank=True) action_name = models.CharField(max_length=50, blank=True) action_value = models.CharField(max_length=50, blank=True) session_date = models.DateTimeField(auto_now_add=True) client = models.CharField(max_length=50, blank=True) I have a dashboard page to show charts and a database page to show the records as a table: blog.urls.py path('', auth_views.LoginView.as_view(template_name='users/login.html'), name='blog-home'), path('<str:username>/dashboard/', views.dashboard and DashboardListView.as_view(), name='blog-dashboard'), path('<str:username>/database/', views.database and SessionListView.as_view(), name='blog-database'), So when you log in, my SessionListView.as_view() goes through the whole database and displays only those records where the Session.client == the url's 'username' value. Example: when user: DummyCo logs in (www.website.com/DummyCo/database/) they see only Session records where the Session.client field is 'DummyCo.' This has worked out great so far. But here is the problem: I now need to provide multiple logins to users to see the same dashboard and database page. Example: jim@DummyCo.com and amy@DummyCo.com both need to see the DummyCo records, but if I provided them with their own logins then their username's in the url would not match and thus the DummyCo records would not show. I thought using the built-in django Groups would be … -
Get user data into django channels, with sessions based authentication
I have user authentication based on django's sessions. (I have several reasons why I don't use default implemented User model) So, basically my simplified authentication view looks like: ... cursor = connection.cursor() cursor.execute("SELECT id, email FROM users WHERE ..") results = cursor.fetchall() request.session['user_id'] = results[0][0] request.session['user_email'] = results[0][1] return redirect('/success_page') This works but then I have problem with channels, when I need to access "user_id" value into consumers.py: Because it's impossible (as I understood) to access session data, outside of views and channels self.scope["user"] is also always AnonymousUser Question: is any way, to access user data into channel consumers, when I have authentication like this? -
How to use a field on a foreign key (another model) as part of my model primary key value
I'm new to Django and I feel sometimes it is not clear in which .py of myApp I should write solutions and examples I see. In my models.py I have a model called Project and a model called Order. In admin section (http://127.0.0.1:8000/admin/myApp/), I would like the user to type a project number when creating a new project. Every project can have multiple Orders. I would like the Order primary key to be composed of the Project number it belongs to, plus a consecutive number. The user can only change the consecutive number part of the Oder primary key but not alter the Project number the order belongs to. For instance for Project with project_number(primary key) = 951, Orders primary keys can be 951-1, 951-2, etc Another project with project_number(primary key) = 1015 can also have orders 1,2, etc but they won't conflict with orders of project 951 because they will be labelled 1015-1, 1015-2, etc. Is it possible to achieve this in models.py? How would I have to modify order_number field below? Notice I need the order_number field to fetch its project_number from order_project field and I won't know the order_project exact value until the user is creating the … -
List of correct urls not displayed in browser when in django debug mode
Normally in debug modewith django, if you type a bad url the browser displays an error message with the list of available urls. like it : Request Method: GET Request URL: http://127.0.0.1:8000/blorp Using the URLconf defined in bricole.urls, Django tried these URL patterns, in this order: admin/ accounts/ [name='home'] accounts/ simple/ (etc...) but in one of my projects, by typing a bad url I have the following result: Request Method: GET Request URL: <a href="http://127.0.0.1:8000/phot" target="_blank">http://127.0.0.1:8000/phot</a> Raised by: django.views.static.serve “C:\Users\Lou\PycharmProjects\photoglide\phot” does not exist and it does not display the list of available urls. in debug the list of urls is not displayed in browser I am with venv (django 3.1.2 and python 3.8 with pycharm) I compared the .py settings with that of a project for which the list of available urls is correctly displayed in the event of a url error and the only difference seems to be: the project where the url debug works : STATIC_URL = '/static/' STATICFILES_DIRS = [str(BASE_DIR.joinpath('static'))] STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles')) STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] ... and where the list of urls is displayed (the project where the url debug works fine): STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] It seems …