Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
connect app on Django to the existing modx revo web site
is it possible to connect the app written on Django to the existing MODX Revo web site? The Django app should use data from MODX Revo database, is it possible? -
Running query in Django view
I have some amount which I am getting from a payment gateway database. Based on the amount that User has bought, I want to fetch some field value from Model. Below is my model. class Subscription(models.Model): """ Add Subscription Pack by Admin """ pack_name = models.CharField('Subscription Name', max_length=255) price = models.PositiveIntegerField('Subscription Price',) no_resume = models.IntegerField('No. of Resume User can Access') def __str__(self): return self.pack_name So if certain price value in the table matches with amount in the payment gateway db, I want to fetch the corresponding no_resume value from Subscription model and append it to a list. Below is the sql that I want to perform in Django view. SELECT no_resume from Subscription WHERE price = amount Thanks in advance.. -
How to write subquery in From clause in django ORM
I wnat to write this query using django orm SELECT depname, empno, salary, enroll_date FROM (SELECT depname, empno, salary, enroll_date, rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS pos FROM empsalary ) AS ss WHERE pos < 3; My current ORm query EmpSalary.objects.values('depname', 'empno', 'salary', 'enroll_date').annotate( pos= Window( expression=RowNumber(), partition_by=[F('depname')], order_by=F('salary').desc(), ) ) I dont know how to get this inot a subquery for the FROM clause. -
Django new post input box dimensions are different than expected
Observed Output Expected Output In the observed output the size of the input box for title and content is different than that expected as in expected output. I am not able to know what am doing wrong. Please help -
AssertionError: Model report.Attendance can't have more than one auto-generated field
Why I can't migrate model ? when run command python manage.py makemigrations i got this error assert not cls._meta.auto_field, ( AssertionError: Model report.Attendance can't have more than one auto-generated field. class Attendance(models.Model): institute = models.ForeignKey(Institute, on_delete=models.CASCADE) employee = models.ForeignKey(Employee, on_delete=models.CASCADE) date = models.DateField() create = models.DateTimeField(auto_now=True) update = models.DateTimeField(auto_now_add=True) on_duty = models.TextField() off_duty = models.TextField() late_time = models.TextField(blank=True, null=True) early_time = models.TextField(blank=True, null=True) status = models.CharField(max_length=100) absent = models.BigAutoField(default=True) class Meta: verbose_name = 'Attendance' verbose_name_plural = 'Attendances' def __str__(self): return self.absent def get_absolute_url(self): return reverse('report:attendance') -
Query to GET x within certain date range in django
I need to get count of users whose deadline are within a certain date range. My Model: class Task_Category(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) def __str__(self): return self.name class Task(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) deadline = models.DateTimeField() cat_id = models.ForeignKey(Task_Category, on_delete=models.CASCADE) when I hit this url I need to get response in this manner where total is the number of people whose deadline lies between start_date and end_date. Url: /api/task?start_date=2020-03-25&end_date=2020-03-26 Method: GET, Output: - Response Code: 200 - { "total": "123" "results": [{ "user_id": 1 "id": 1, "name": "Science Task 1", "deadline": "2020-03-25T08:12:05" }] } I tried : class Task(APIView): def get(self, request) start_date = request.GET.get('start_date') end_date = request.GET.get('end_date') task_qs = Task.objects.filter(deadline__range=(start_date, end_date)).annotate(count=Count('id')) response = {"total": task_qs.count, "results": []} for obj in task_qs: response["results"].append({"user_id": obj.id, "name": obj.name, "deadline": obj.deadline}) return Response(response, status=status.HTTP_200_OK) But only count is not working. -
Datetime is wrong in django
I am in Eastern Standard Time (EST). Daylight savings time started 2 weeks ago, where clocks were turned forward 1 hour (so 5PM became 6PM). I have USE_TZ = True. In my app, I have a form that submits a date, like 2AM. That date, still 2AM, gets saved in a model: event.start = date. I have a view that renders the date, and the page shows 2AM correctly. The problem: event.start evaluates to 3AM (EST) / 8AM (UTC), 1 hour later that what it's supposed to be! The input was 2AM, it even renders 2AM in templates, but for some reason internally event.start is 8AM (UTC) / 3AM (EST). But for some reason django.utils.timezone.now() gives me the correct time 2AM, instead of 3AM. My OS system time also gives the correct time, 2AM. I want to schedule a job for 2AM, but it ends up getting scheduled for 3AM instead because event.start is set to 3AM for some reason! I want to keep times in UTC. How do I deal with this? -
Django rest framework, redirect after making post
I have an API build with the Django rest framework. There is a post where a user inputs some data, And, a retrieve method in my view that renders an HTML page based on the data from the post. There's a field in the post called 'mission_name' which is a primary key so when a user inserts the mission name to the end of the URL line it runs the retrieve method. mission name : testredirect http://127.0.0.1:8000/twosecondgdt/testredirect/ Will open the page. How do I redirect the retrieve method upon a successful post? # views.py from __future__ import absolute_import from django.shortcuts import render from rest_framework.viewsets import ModelViewSet from Project_Level.database_consts import THREE_POINTS_TRINAGULATION from Project_Level.postgres_queries import HTMLFileInteractionWithDB from .serializers import PointsSerializer from .models import Points from Project_Level.base_objects import GeoPoint from .second_GDT_finding.app import MainApp class PointsViewSet(ModelViewSet): # Return all missions ordered by id, reversed. queryset = Points.objects.all().order_by('-id') serializer_class = PointsSerializer data = queryset[0] serialized_data = PointsSerializer(data, many=False) points = list(serialized_data.data.values()) def retrieve(self, request, *args, **kwargs): mission_name = self.points[1] assign_gdt = GeoPoint(lat=self.points[2], long=self.points[3]) gdt1 = [assign_gdt.get_lat(), assign_gdt.get_long()] assign_uav = GeoPoint(lat=self.points[4], long=self.points[5], elevation=self.points[6]) uav = [assign_uav.get_lat(), assign_uav.get_long(), assign_uav.get_elevation()] area_name = f"'{self.points[-2]}'" try: # Check if a file already exists in the DB. HTMLFileInteractionWithDB.table = THREE_POINTS_TRINAGULATION openfile … -
MultipleObjectsReturned get() returned more than one KVStore
I'm using django sorl-thumbnail for managing thumbnails and I have following error MultipleObjectsReturned at 'some-url' get() returned more than one KVStore -- it returned 2! Do you know how to handle this problem? -
Django Generic Views, see user_information of a friend request
I have a question regarding the generic views. They are still hard to handle. So I did a post request to a specific user to add him/her as my "friend". Now she ?he should be able to see all the informations about the "friend_request_sender". I have no idea if I am on the right path, so it would be great if you can help me. Here is my code: urls.py urlpatterns = [ path('friends/request/<int:user_id>/', SendFriendRequest.as_view()), path('friends/requests/<int:friend_request_id>/', GetFriendRequest.as_view()), ] model.py (FriendsRequest) class FriendsRequest(models.Model): receiver = models.ForeignKey(to=User, related_name="request_sender", on_delete=models.CASCADE) sender = models.ForeignKey(to=User, related_name="request_receiver", on_delete=models.CASCADE) REQUEST_STATUS =( ('s', 'sent'), ('p', 'pending'), ('a', 'accepted'), ) status = models.CharField(max_length=1, choices=REQUEST_STATUS, default="p") model.py (User) class User(AbstractUser): username = models.CharField(max_length=50, unique=True) email = models.EmailField(unique=True) first_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) date_joined = models.DateTimeField(auto_now_add=True) followees = models.ManyToManyField(to=settings.AUTH_USER_MODEL, related_name='followers', blank=True) views.py class GetFriendRequest(ListAPIView): serializer_class = UserSerializer queryset = User.objects.all() lookup_url_kwarg = 'friend_request_id' def get_object(self): friend_request_id = self.kwargs.get(self.lookup_url_kwarg) friend_information = User.objects.filter(id=friend_request_id) return friend_information -
How to make an online user authentication with python?
Right now I am currently working with Django and Django-Rest-Framework and also want to create a desktop application that allows users to login online by checking the username and password from server(Django) I wanted to know how to make an online user authentication with python like steam? I wrote a simple example myself but I don't think it's the right choice: What I Do : I made an API in Django-Rest-Framework to check username and password and it returns json result that tell you the username and password is correct or not. Django:views.py class UserLoginCheckViewSet(APIView): queryset = User.objects.all() serializer_class = UserSerializer(queryset) def get(self,request,format=None): is_username_correct = False is_password_correct = False try: user = User.objects.get(username=request.GET['username']) is_username_correct = True if user.check_password(request.GET['password']): is_password_correct = True except: return Response({'username':is_username_correct},status=HTTP_400_BAD_REQUEST) return Response({'username' : is_username_correct,'password':is_password_correct},status=HTTP_202_ACCEPTED) And i test the api with this : Client:test.py import requests login = False url = 'http://127.0.0.1:8000/api/v1/logincheck' while not login: print("--------------------Login Page-----------------") user = input('Enter Username : ') password = input('Enter Password : ') detail = { 'username': user, 'password': password } x = requests.get(url, detail) json = x.json() if not json['username']: print('Wrong Username!') break elif not json['password']: print('Wrong Password!') break elif json['username'] & json['password']: print('Logged In Successfully!') login = True But … -
Django - Dealing with extra slash of URLField while saving with unique=True
I have model which have URLField set to unique item_url = models.URLField(max_length=255, unique=True) Problem is when I get data from frontend(VueJS) I might get URL with extra slash. e.g. I have below URL in my db: https://themeforest.net/item/vuesax-vuejs-admin-dashboard-template/23328599 and User sent request with same url but with trailing slash like below: https://themeforest.net/item/vuesax-vuejs-admin-dashboard-template/23328599/ In this case, unique validation thinks it is two different URL but actually both of them are same. Plus, it will be better to store URLs without trailing slashes. So, What is the best way to handle it? Does Django provides something to handle this kind of scenario? I am using Django + DRF. Thanks -
Is there a django tutorial which clearly describes google OAuth?
I am learning django and setting up a website which does the following. Show google OAuth page Get access token (and mail id) and check whether a user is previously logged in using this google account by searching through database. If previously registered,fetch his details and show them If user logs in for the first time,then show a page to enter some info. Setup cookies or something similar in user's browser to avoid logging in everytime he visits the side(Unless user deletes cookies,etc) Logout option I went through many tutorials.None of them explain the above 3,4,5 points.Is there an example tutorial (or a series of tutorials) or a sample project which explains all the above steps? I need something which covers everything. This tutorial comes close but there is no guidance on how to do 3,4,5.(This tutorial uses fb,instagram logins) Any link or guidance is much appreciated.Thanks for answering. -
Django not sending POST data when they are empty
I have this strange issue. When I'm sending no data in an array, django removes the attribute from the request.data. Annoying because I want to catch an error when it's empty + on swagger it does send the data in the request.data. i.e.: with this code only name will be send test_group_3 = GroupFactory(name="test_no_sites_given_group") sites = [] # Execute the patch operation response = self.client.patch( url, data={"name": test_group_3.name, "linked_sites": sites} ) when I pass a site into the sites array, sites will be passed. How can I pass the attribute, even if it's empty? I searched for a solution but, strange enough, there are no related questions.. -
Django loging page
Hallo, the dropdown list cannot be opened on the login page. On other pages it can be oppened. I used: the Django authentication system django.contrib.auth, bootstrap-4.2.1.min.js jquery-3.3.1.min.js popper-1.12.9.min.js There is no mistake only the dropdown cannot be opened on loging page. Hier is image <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle active" href="#" id="dropdown-projects" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{% trans 'base.projects' %}</a> <div class="dropdown-menu" aria-labelledby="dropdown-user"> <a class="dropdown-item" href="{% url 'proj:index' %}">{% trans 'base.overview' %}</a> <span class="dropdown-item">------------</span> {% for proj in projects %} <a class="dropdown-item" href="{% url 'proj:detail' pr.id %}">{{proj.pr_number}} {{pr.o_name}}</a> {% endfor %} </div> </li> -
django development server not serving static files
Same question as this 7 year old one but the solutions don't help plus I'm using django 3 so in my opinion clearly not a duplicate. I followed exactly the Django documentation about static files. settings file: STATIC_URL = '/static/' DEBUG = True Folder Structure: ---my_project ------my_project ------app1 ------static ---------css ------------mystyle.css Template: {% load static %} <link rel="stylesheet" href="{% static "css/mystle.css" %}"> When browsing to the site I get a 404 Not Found. The link is pointing to the correct directory: http://127.0.0.1:8000/static/css/mystyle.css With further search and looking at the documentation (which in my opinion is unclear) I also found the setting STATIC_ROOT and set it accordingly but that did not help either. #BASE_DIR = path to project dir STATIC_ROOT = os.path.join(BASE_DIR, 'static') What am I doing wrong? -
how to switch input formats in a single page, with django?
So I'm a beginner in Django and having trouble in creating a function. What I'm trying to do is this : It is basically an input page, with two radiobuttons-(1) Full text (2) Simple text. So if the user clicks the "Full Text" button, a large textarea is displayed and he/she can input long texts. If the user clicks the "Simple Text" button, one small textarea shows up and he/she can input, say, one sentence. In short, the input field switches with the radio button. + There is a '+' button in the latter, so the if the user clicks '+' button he/she will get additional textarea, as many as he wants. Like the form of tag. I have no idea on how to write this code. I'm not sure if my description is clear enough, but I very much appreciate your help :) -
tensorflow.python.framework.errors_impl.InvalidArgumentError: Tensor specified in either feed_devices or fetch_devices was not found in the Graph
I'm using a Keras Functional API to save a model and then re-load from HDFS Server during one-time initialization of code: import keras from keras.models import Model trained_model = # Build model layers from scratch trained_model.set_weights(weights_pickle_file) trained_model._make_predict_function() And then after initializing this once, I use this model to make predictions one at a time, and we make predictions using the function: predictions = trained_mdoel.predict(data) When running on our Dev Environment without using the Django web service, this code runs fine, but when using Django, we get the following error: tensorflow.python.framework.errors_impl.InvalidArgumentError: Tensor specified in either feed_devices or fetch_devices was not found in the Graph Our Keras and tensorflow versions are listed below: Keras: 2.3.1 TensorFlow: 2.0.0 Previously, we've looked through a lot of solutions for this problem, but most of them are for the tensorflow.keras library, or are for older versions of TensorFlow, where could access the session variable. Solutions that didn't help our case: InvalidArgumentError: Tensor embedding_1_input:0, specified in either feed_devices or fetch_devices was not found in the Graph Keras (Tensorflow backend) Error - Tensor input_1:0, specified in either feed_devices or fetch_devices was not found in the Graph keras and tensorflow(backend error) Tensor conv2d_1_input:0, specified in either feed_devices or fetch_devices … -
Can we Count API HIT's using Throttling in Django DRF
I created some API using Djanago- DRF. Now, I want to count the API HIT's through Throttling and if total count is reached 500 user will deative mode(is_active = False) So, any idea how can do this through throtting. if any other approach is there plz suggest me -
convert string type to byte without encoding
my program output is string like this string = "b'\xda\xaf\xd9\x84\xd8\xb3\xd8\xaa\xd8\xa7\xd9\x86'" i need to change string type to byte bytes = b'\xda\xaf\xd9\x84\xd8\xb3\xd8\xaa\xd8\xa7\xd9\x86' How can I do this? -
How to manually trigger client side form validation in django with JS/JQuery?
Suppose I am displaying a form with template: <form id="theform" action="" method="post"> {% csrf_token %} {{ form.non_field_errors }} {{ form.source.errors }} {{ form.source }} {{ form.a_field }} <input type="submit" value="submit"> </form> Note that, a_field has also a NumberInput widget created with ModelForm from a model. So it already has some validations (e.g. like "Please enter a number" when non-numeric character is entered). So I want some additional client-side validation on a_field before submitting which will trigger an error popup just like Django error messages when validation returns false. Something like this: $('#theform').submit(function (e) { val = $("#id_a_field").val(); e.preventDefault(); if( /* check if val is ok */ ) { <-- The validation is done here. this.submit(); } else { // <-- Here I want to trigger a validation error similar to django validation error message } }); Is there a way to do it? -
How to display information media_file in html file?
I want to get the information in media_file to be displayed on the html file page. But my problem is that if in media_file I put video, music, image data in html, how do I check it? models.py class Adddata(models.Model): media_file = models.FileField(upload_to="uploads/%Y/%m/%d/", blank=True) def _is_type(self, mimename): if not self.media_file: return False filetype = mimetypes.guess_type(self.media_file.name)[0] return filetype and filetype.split("/")[0] == mimename def is_audio(self): return self._is_type("audio") def is_video(self): return self._is_type("video") def is_image(self): return self._is_type("image") page.html {% if ............ %} I don't know how to check. <video controls> <source src="{{ adddata.media_file.url }}" type="video/mp4"> </video> <audio controls> <source src="{{ adddata.media_file.url }}" type="audio/mp3"> </audio> <img src="{{ post.media_file.url }}" alt="img"> {% endif %} I want to check if it is video type. To show in video type, if in song, then show in song type Image showing image types. How do I check? Can someone help me? Thanks -
HOW TO PASS AN ID INTO THE TEMPLATE AND RETRIEVING DATA
I am getting so difficult to pass an id into the template,here is my views.py file def add_academy(request,pk): child=get_object_or_404(Child_detail,pk=pk) academy=Academic.objects.filter(Student_name=child) context={ 'academy':academy, } return render(request,'functionality/more/academy/add.html',context) Also this my urls.py file from . import views from django.urls import path urlpatterns=[ path('add_academy/<int:pk>/',views.add_academy, name='add_academy') ] And this is my template <div class="container"> <td><a href="{% url 'add_academy' child.id %}"> <button type="button" class="btn btn-primary">Add Academic details of a child</button> </a> </td> It show me an error that state that NoReverseMatch at /academy/add_academy/3/ Reverse for 'academy' not found. 'academy' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/academy/add_academy/3/ -
python_http_client.exceptions.BadRequestsError: <HTTPError 400: 'Bad Request'> in Django sendgrid
I'm using sendgrid to send a mail in my Django project. If i call my sendgrid function from views, it's working. But if i call from celery it's throwing error python_http_client.exceptions.BadRequestsError: <HTTPError 400: 'Bad Request'>. I don't know why i'm getting this error. Checked the python version in Both places(Same in Both places). Code references: Mail.py from_email="support@xxx.com", to_emails=user['email']) message.dynamic_template_data = { 'name': user['firstname'] } message.template_id = os.getenv('TEMPLATE_ID') try: sg = SendGridAPIClient(os.getenv('SENDGRID_API_KEY')) sg.send(message) except urllib.HTTPError as e: print(e.read()) exit() This issue is little weird, i don't know why it's happening. Can anyone help to solve this. -
Django Parler also shows translated object on the admin list
I use django 2.2.11 and django-parler 2.0.1. I created a model using TranslatableModel and TranslatableAdmin. Then I created an object and filled the translatable fields of the same object for the second language. When I get to the model list page, I see two objects in the list for the same object. Although two objects appear on the list, 1 object is written at the bottom of the list. (As you can see on the screenshot below) I also got same result with django 2.0.7 and django-parler 1.9.2. Where could I have made a mistake, can someone help?