Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hexadecimal value is shown in redis server
I am using django-redis library in django.I am trying to store data in redis server using the following code #settings.py CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', }, } } #views.py from django.core.cache import cache @action(detail=False) def get_random_questions(self, request): questions = Question.objects.all() cache.set('foo', 'bar') serializer = self.get_serializer(questions, many=True) return Response(serializer.data) and when I execute the "scan 0" command in the redis-cli I get the following response 1) "0" 2) 1) "example:1:foo2" 2) "example:1:foo" 3) ":1:foo2" 4) ":1:foo" 5) "test" 6) ":1:foo1" 7) "example:1:foo1" 8) "employee" I am not able to understand where :1:foo came from. And when I am using "get :1:foo" command, I am getting the following response "\x80\x04\x95\b\x00\x00\x00\x00\x00\x00\x00\x8c\x04bar\x9". Again I don't understand why is this happening? -
Django - Search in generated form
so I have a class "Business" and a Form / View to add a specific model which requires a business to be selected. I used: class make_xy(Form): fields = ['business'] Now I want users to be able to enter a searchstring to filter they objects presented. So altered to the following: class make_xy(Form): Search = forms.CharField(required=False) Business = forms.ModelMultipleChoiceField(queryset=Business.objects.all()) But I ran into multiple problems. So now my question: How would you build a form where users can search for a matching aspect (i.e. name) and will be presented with the matching objects so they can select one of them -
How do I apply a function to an certain object?
I want to create a method that works on a method, like this, inside the 're' python module: _compile(pattern, flags).finditer(string) the function finder is being applied on _compile, How? does the return type of _compile is string, and if it's so how can it possible to create methods that applies on strings? -
Check if a list exists in my database by querySet django
I'd like to verify if a list of variables exist in my database I tried this: if Magazine.objects.filter(mag=post.mag_no, prodc_magt_no__in[post.cn1,post.cn2,post.cn3,post.cn4) but this queryset is check at least one value, I wanna check the whole list:post.cn1,post.cn2,post.cn3,post.cn4 in my database column = prodc_magt_no note: mag=post.mag_no is necessary! -
django : Update two models using same API call
I have an API call which gets and receives the user data, User model looks something like this - I have a model for user - { "id": 23, "name": "fname", "height": null, "weight": "59", "blood_pressure": "131", "blood_sugar": "320", "email": "m@gmail.com", } I want to save this data to be saved in UserBody model - "height": null, "weight": "59", "blood_pressure": "131", "blood_sugar": "320", while I want rest of the data(id, name, email) to be saved in BodyModel My User model looks like this - class MyUser(AbstractBaseUser, PermissionMixin): name = models.CharField(max_length=63, blank=True) height = models.IntegerField(blank=false, null=false) weight = models.IntegerField(blank=true, null=false) blood_pressure = models.IntegerField(blank=true, null=false) blood_sugar = models.IntegerField(blank=true, null=false) email = models.CharField(max_length=63, blank=True) Class UserBody - class UserBody(AbstractBaseUser, PermissionMixin): user = models.OneToOneField(MyUser, on_delete=models.CASCADE) height = models.IntegerField(blank=false, null=false) weight = models.IntegerField(blank=true, null=false) blood_pressure = models.IntegerField(blank=true, null=false) blood_sugar = models.IntegerField(blank=true, null=false) I fiddled with making the user object foreignKey but I just can't wrap my head around how it should have worked. I have a MyUser serializer, but I just don't know how to write a serializer for UserBody model. Help me with any direction, I will take it forward from there. -
Django annotate complex subquery count
I have the following model: class Visit(models.Model): ... device_id = models.CharField(...) created_at = models.DateTimeField(auto_now_add=True) ... This model basically denotes a visit to a place, device_id uniquely identifies a person, and same person can visit a place multiple times, hence creating multiple enties in this table. I'm building analytics methods on top of this model. One thing I want to do is, for the last 30 days, display number of people that visitied only once within that day. With a basic approach, I can issue a db query for every single day like this: for date in dates: start_time = date end_time = date + datetime.timedelta(days=1) Visitor.objects.filter( site__in=node_descendants, created_at__gte=start_date, created_at__lt=end_date) ).values('device_id').annotate(visit_count=Count('device_id')).filter(visit_count=1).count() Now I want to calculate data for each day in the 30 day range with a single query, using a Subquery like this: single_visitor_query = Visitor.objects.filter( created_at__date=OuterRef('truncated_date') ).order_by().values('device_id') .annotate(visit_count=Count('device_id')).filter(visit_count=1) .annotate(count=Count('*')).values('count') chart_data_query = Visitor.objects.filter( created_at__gte=start_date, # Start of month created_at__lt=end_date, # End of month ).annotate( truncated_date=TruncDay('created_at') ).values('truncated_date').distinct().annotate( single_visitor_count=Subquery(single_visitor_query[:1], output_field=PositiveIntegerField() ) I have a couple of problems with this approach: count resulting from the subquery is not the count of all items having visit_count=1, but they are all 1. I know the subquery is somewhat off, but I can't see how I … -
Filtering querysets for nested models
Stack Overflow world! I am making a News App API and I want to create an APIView with comments for a speicific Post that also lets users posting comments for the specific post. These are my models (simplified): Post: class Post(models.Model): title = models.CharField(max_length=250) text = models.TextField() Comment: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=200) text = models.TextField() And view: class CommentList(generics.ListCreateAPIView): queryset = Comment.objects.filter(post=???) serializer_class = CommentSerializer First, how do I create a list of comments for an instance of Post? Second, is it the correct approach or should I try something else? -
getting info through API calls and authenticating
I want to make a Website that makes API calls to a server i have bought and we get back details about a user and use those details to create a authentication system. i need to use these few lines to do it import requests url = "*************.com.login" querystring = {"username":"username","password":"password"} response = requests.request("GET", url, headers=headers, params=querystring) jData = response.json() i ham trying to integrate this with the inbuilt django authentication system. How should i do it. any help appreciated Thanks.. i have tried something like this class AuthenticationBackend(backends.ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): usermodel = get_user_model() try: #user = user.objects.get(username=username) # API Call lms_url = "http://"*************.com/login" querystring = {"username":username,"password":password} #queryString = {"username":username,"password":password} response = requests.request("POST", lms_url, params=querystring) jData = json.loads(response.text) if jData['code'] == '200': user = User.objects.get(username=username) return user else: return None url = "*************.com/login" querystring = {"username":"username","password":"password"} response = requests.request("GET", url, headers=headers, params=querystring) jData = response.json() -
Django: Group by model parameter and Count
I have 2 models: class FaultType(models.Model): name = models.CharField(max_length=255, blank=False, default='') visible = models.BooleanField(default=True) And class RunFault(models.Model): run = models.ForeignKey(Run, on_delete=models.CASCADE) fault_type = models.ForeignKey(FaultType, on_delete=models.CASCADE) note = models.CharField(max_length=100, blank=True, default='') I need to group all instances of RunFault by FaultType, and count them. Preferably obtain a dictwith structure (example): faults = { "some_fault" = 7, "foo_fault" = 4, "bar_fault" = 13 } (Where "blabla_fault" is FaultType.name) Right now I'm querying the DB like so: faults = RunFault.objects.values('fault_type__name').order_by('fault_type').annotate(count=Count('fault_type__name')) But that returns a list of dicts like so: faults = [ {"fault_type__name": "some_fault"}, {"count": 7}, {"fault_type__name": "foo_fault"}, {"count": 4}, {"fault_type__name": "bar_fault"}, {"count": 13} ] Is that the intended behaviour of .annotate(count=Count('some_key')) ? Or am I doing the wrong query? -
Django Rest Framework Update model on POST
I am working with an api that uses POST to both create and update data, I am trying to get rest_framework to use update_or_create to check to see if the object is there before just objects.create(). I want to override the create function in the ModelSerializer class but I cant get it to update, whenever I make a POST request it just gives me a 400 error already exists Here is my serializer from rest_framework import serializers from metrics.models import * # Company Serializer class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = "__all__" def create(self, validated_data): company, updated = Company.objects.update_or_create(**validated_data) company.save() return company Viewset from metrics.models import * from rest_framework import viewsets, permissions from .serializers import * import json # Company Viewset class CompanyViewSet(viewsets.ModelViewSet): queryset = Company.objects.all() permissions_classes = [ permissions.AllowAny ] serializer_class = CompanySerializer -
How to pass data through the url in Django 2.2 and how to get the data using an AJAX get
My Django URL: urlpatterns = [ re_path(r'^data/change_title/$', views.changeAbstractTitle, name='changeAbstractTitle') ] This is the HTML table row that I am refering to with the AJAX: <td><a href="{{ item.get_absolute_url }}" id="outer_title" pmid={{ item.pmid }}>{{ item.abstractTitle }}</a></td> <tr style="background-color:white;border-style:solid;border-color:#DDDDDD;border-width:1px"> <th style="padding:10px;">Abstract Title</th> <td style="padding:10px;"><input id="abstract_title" pmid={{ item.pmid }} type="text" size="60" value="{{ item.abstractTitle }}"></td> <td style="padding:10px;"><input id="send" class="btn btn-success" onclick="change_title({{ item.pmid }} , '{{ item.subjectArea_id }}')" type="submit" value="Submit" style="padding:10px;"></td> </tr> This is my AJAX method: function change_title(pmid, subjectArea_id) { $.ajax({ url: `/data/change_title/?id=${pmid}` + `&subjectArea_id=${subjectArea_id}` + "&abstract_title=" + $(`[id*=abstract_title][pmid*=${pmid}]`).val(), type: 'GET', success: function (data) { $(`[id*=outer_title][pmid*=${pmid}]`).html(data["new_title"]); }, error: function (data) { alert("Unable to communicate with 2.7 Backend"); } }); } I am not sure how to pass the data through the URL so I can get it with my Ajax function. I am using Django 2.2. Thank you so much for your help. -
can i add Paginator to search result with chain (multiple models ) using django?
i'm asking if i can add Paginator to search result with chain (multiple models ) using django if yes how to do that please ? any idea will help me , -
Django: How to request data and simultaneously have it editable
I have a simple app that gets user input and when a button is clicked, the input is saved as an entry on the database. I'm thinking of creating another app that not only displays the same information (think of view profile) but also simultaneously lets the user edit the text that is displayed in the text field. I'm guessing the solution is to have the text-fields be auto-filled by pulling the data from the database, and allow overwriting the data once the submit button is clicked. -
Show a list of Posts in a different URL
Django comes with an out of the box index.html where it shows a list of all posts. I need to show this list in a new URL, when I somply copy the html code from index.html and paste onto planoacao.html it doesn´t show anything. This is the index.html: {% for post in post_list %} <div class="card mb-4" style="width: 18rem; "> {% if post.get_finalizado_display == 'Não' %} <!--<p class="card-text text-muted h6"> NOK </p>--> <div class="card-body" style="background-color:#FF0909;"> {% else %} <!--<p class="card-text text-muted h6"> ok </p>--> <div class="card-body"> {% endif %} {% endfor %} This is my views.py: from django.views import generic from .models import Post class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' class Calendar(generic.DetailView): model = Post template_name = 'calendar.html' class Planoacao(generic.DetailView): model = Post template_name = 'planoacao.html' This is my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), url(r'^planoacao/', TemplateView.as_view(template_name="planoacao.html")), url(r'calendar', TemplateView.as_view(template_name="calendar.html")), url(r'^admin/', admin.site.urls), url(r'^', include('blog.urls'), name="Blog"), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) How can I show a list of all posts in a different URL? xxx/planoacao.html ? Simply copying the html from index.html doesn´t work. Note that I don´t want to change the regular index.html post list, I just want … -
Forms are not getting deleted from formset after is_valid() check
I have forms that can be dynamically added and deleted from a formset. On the front end, I mark deletion by checking the "delete" checkbox included in the form. form-0-DELETE gets added to the POST automatically. https://docs.djangoproject.com/en/2.2/topics/forms/formsets/#dealing-with-ordering-and-deletion-of-forms Deleting form from django formset def edit(request): Formset = formset_factory(EditForm, extra=1, can_delete=True) if request.method == 'POST': formset = Formset(request.POST) if formset.is_valid(): cleaned_data = formset.cleaned_data print(cleaned_data) return render(request, '/edit.html', {'test': 'Post'}) else: formset = Formset() return render(request, '/edit.html', {'formset': formset}) Here is part of the return formset: data: {u'form-MAX_NUM_FORMS': [u'1000'], u'form-0-test': [u'72'], u'form-0-DELETE': [u'on'], u'form-TOTAL_FORMS': [u'0'], u'form-INITIAL_FORMS': [u'0'], u'form-0-weight': [u'1']} deleted_forms: [] 'test' and 'weight' are input values in the forms. You can see 'form-0-DELETE' there. Meaning the delete event was added to the POST with the default value 'on.' One of my links said to change this value to something that could be evaluated to true, setting it to True, true, and 1 didn't change anything. TOTAL-FORMS is correctly 0 as I keep track of additions and deletions, but I would expected deleted_forms to be populated with form-0. This is a problem when I have more than 0 forms, as I don't know what will be in cleaned data since deleted forms aren't … -
Django steps or process logging via REST
For learning purpose I want to implement the next thing: I have a script that runs selenium for example in the background and I have some log messages that help me to see what is going on in the terminal. But I want to get the same messages in my REST request from Angular app. print('Staring') print('Logged in') ... print('Processing') ... print('Success') In my view.py file class RunTask(viewsets.ViewSet): queryset = Task.objects.all() @action(detail=False, methods=['GET'], name='Run Test Script') def run(self, request, *args, **kwargs): task = task() if valid['success']: return Response(data=task) else: return Response(data=task['message']) def task() print('Staring') print('Logged in') ... print('Processing') ... print('Success') return { 'success': True/False, 'message': 'my status message' } Now it shows me only the result of the task. But I want to get the same messages to indicate process status in frontend. And I can't understand how to organize it. -
Django homepage without cookie before login
I see "we are using cookies" everywhere. I want to have my homepage without a cookie, if no one is logged in. I am using some REST-queries, if someone is logged in, so later on cookies are needed. Is that possible with django ? How ? I am using django 2.2.6. -
Django- "python manage.py runserver" not working
Hi im new to django and i cant get my web server running. First of all i viewed several of other threads and ive been searching for a solution for 4 hours and i couldn't find any help. So this is what ive done: Installed django using the following "pip install django" Created a project using "django-admin startproject DjangoProject" Went into the directory using "cd DjangoProject" Inputted "python manage.py runserver" into the console and the console doesn't display anything. So ive tried several of methods to solve this issue and have even set up environmental variables C:\Python37\scripts C:\Python37 After setting up environmental variables when i input "python -m django --version" or "python manage.py runserver" i receive an output of "'python' is not recognised as an internal or external command,operable program or batch file." I think i haven't set up my environmental variables properly Have i set up my environmental variables properly? Or have i done something else wrong, I can't seem to figure out the problem. Any Help would be appreciated. -
How I can update my objects in template dynamically?
I have comments on a product on the page. and there is a button to add a comment, which puts a new comment into the database. How can I automatically display a new comment on a page? mytemplate.html <div id="comments"> {% include 'comments.html' %} </div> comments.html {% for comment in comments %} <!-- some code for display comments --> {% endfor %} script.js $("#addComment").on("click", function(e){ e.preventDefault() if ($("#addCommentArea").val() != ""){ data = { commentText: $("#addCommentArea").val(), product_id: "{{ product.id }}" } $.ajax({ type: "GET", url: "{% url 'newcomment' %}", datatype: 'json', data: data, success: function(data){ $("#addCommentArea").val("") } }) } }) -
Type object 'Token' has no attribute 'DoesNotExist'
In urls.py, I added token-auth url and I can successfully get token with right credentials: from rest_framework_jwt.views import obtain_jwt_token .... path('token-auth/', obtain_jwt_token), In Postman I tried to hook this method with jwtToken variable like this: var data = JSON.parse(responseBody); postman.setEnvironmentVariable('jwtToken', data.token); Than I tried to call another URL which starts like this: class MyRequestView(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication, ) def list(self, request): .... In postman, when I call this method I tried to add an Authorization header: Authorization: Bearer {{jwtToken}} // Response: "Authentication credentials were not provided." Authorization: JWT {{jwtToken}} // Response: "Authentication credentials were not provided." Token returns a different response: Authorization: Token {{jwtToken}} > WrappedAttributeError at /mypath type object 'Token' has no attribute 'DoesNotExist' I also tried to add a Bearer Token manually but I still get "Authentication credentials were...." I added rest_framework_jwt among INSTALLED_APPS and my DEFAULT_AUTHENTICATION_CLASSES config has TokenAuthentication, SessionAuthentication and BasicAuthentication. What am I missing? -
Changes to the database are displayed only after restarting gunicorn
The data obtained in the NextPredictionListView in the prediction_next_list.html template is updated immediately. And in LastPredictionsListView (prediction_last_list.html) only after restarting gunicorn. class NextPredictionsListView(ListView): model = Prediction queryset = Prediction.objects.filter(prediction_result=None) template_name = 'app/prediction_next_list.html' class LastPredictionsListView(ListView): queryset = Prediction.objects.filter(~Q(prediction_result=None), date__lt=datetime.now()) template_name = 'app/prediction_last_list.html' -
How to generate unique results is django queryset?
I'm retriving a set of objects in django view using following query: shuffle(query) query2=list(ChannelPost.objects.annotate(num_images=Count('channelpostmedia')).filter(num_images__gt=0).order_by('-user_like').distinct()[:6]) query4=list(CommunityPost.objects.distinct().annotate(num_images=Count('communitypostmedia')).filter(num_images__gt=0).order_by('-user_like')[:16]) query3=list(Communities.objects.distinct().order_by('-points')[:5]) query5=list(channel.objects.distinct().order_by('-chaneldate')[:9]) shuffle(query2) shuffle(query3) shuffle(query4) shuffle(query5) query6=list(post.objects.order_by('-DatePosted')) The main problem with the queryset is the fact that the result always contain duplicate objects which is undesirable. -
AttributeError: 'Settings' object has no attribute 'MEDIA'
I'm trying to do (shopping cart web page) using python and django I'm getting this error when I try to run (python manage.py makemigrations) File "D:\projects\myenvironment\lib\site-packages\django\conf__init__.py", line 57, in getattr val = getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'MEDIA' this is the link for the project on GitHub https://github.com/aaheggy/shoppingWeb Please Help enter image description here -
How to set python timedelta < 0 condition on html
I'm creating a condition on my HTML template and the condition needs to check if a particular timedelta is negative or not. {% if discrepancy.CurrentDiffs < 0 %} Do something {% else %} Do something else {% endif %} It doesn't throw any error but it runs the code in the else statement. -
Getting an Error when running makemigrate on Product model fields that have been added to an existing model
Admittedly I’m a newbie to django and I’m getting the following error when trying to run python manage.py makemigrations I’m trying to add a new field in to my class Product(models.Model): featured = models.BooleanField() Code from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length=120) # max_length = required description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=10000) summary = models.TextField() featured = models.BooleenField() #only new added line Error: AttributeError: module 'django.db.models' has no attribute 'BooleenField' command: python manage.py makemigrations <enter> entire_traceback: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\.....\trydjango\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\.....\trydjango\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\.....\trydjango\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\.....\trydjango\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\.....\trydjango\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\.....\trydjango\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\.....\src\products\models.py", line 4, in <module> class Product(models.Model): File "C:\.....\src\products\models.py", line 9, in Product …