Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Npm package in Django isn't working on Heroku
I installed a package using npm in my Django app and then moved the folder to my static folder and imported it to base.html with <script src="/static/js/convertapi-js/lib/convertapi.js"></script> This works fine on localhost but when I deploy the app to Heroku it can't find the file. I'm new to Django so any help would be appreciated. -
Ordering Django Chained Queryset
I have a search page which pulls a request from several models and compiles them into separate querysets which are then combined using the chain() function before being rendered to the template. The views.py file looks like this: class SearchResults(ListView): template_name = 'front_end/search_page.html' context_object_name = 'query' def get_queryset(self): query_param = self.request.GET['q'] film_search = Film.objects.filter(Q(title__icontains=query_param)).distinct().order_by('-gross') actor_search = Actor.objects.filter(Q(name__icontains=query_param)).distinct().order_by('-career_gross') director_search = Director.objects.filter(Q(name__icontains=query_param)).distinct().order_by('-career_gross') writer_search = Writer.objects.filter(Q(name__icontains=query_param)).distinct().order_by('-career_gross') return list(chain(film_search, actor_search, director_search, writer_search)) This code works but I want to order the final list by 'career_gross' and 'gross' with the instance with the largest value for either of those attributes appearing first in the list. This is a problem as the querysets come from different models - I cannot order the chained list using order_by('career_gross') like I did before (not to mention not all models have a 'career_gross' attribute). To put it simply, can I order chained querysets by the value of different attributes coming from different model instances. -
Hi am new to Django, i want to get the system user/computer name who is accessing my website on intranet and store the hits into a sqlite DB table
how can I get the system/computer/user name of user who is accessing my website on internal network. I want to record the end user hits and to store them in SQLite DB -
django-import-export empty rows before csv header trigger exception while importing
While importing data from csv, I realized that this error is triggered if the first row is not the header list indices must be integers or slices, not str first_name,last_name,email,password,role Noak,Larrett,nlarrett0@ezinearticles.com,8sh15apPjI,Student Duffie,Milesap,dmilesap1@wikipedia.org,bKNIlIWVfNw,Student It only works if the first row is the header first_name,last_name,email,password,role Noak,Larrett,nlarrett0@ezinearticles.com,8sh15apPjI,Student Duffie,Milesap,dmilesap1@wikipedia.org,bKNIlIWVfNw,Student ... I tried overwriting before_import to remove any blank row def before_import(self, dataset, using_transactions, dry_run, **kwargs): indexes = [] for i in range(0, len(dataset)): row = ''.join(dataset[i]) if row.strip() == '': indexes.append(i) for index in sorted(indexes, reverse=True): del dataset[index] return dataset This works for all the rows, except the first row which should always contain the header, and if not the error is thrown. -
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?