Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get the error 'Authentication credentials were not provided' even after passing the token in the headers
Im trying to get all the todos that created by the user api/todo, and get the user api/auth/user.. but I keep getting this error: { "detail": "Authentication credentials were not provided." } in the frontend I'm sending the headers (tried both in the body, in query, nothing is working) const config = {headers: {Authorization: `Token ${token}`}} so I tried in postman, in Headers tab to send the token - Authorization:Token fcabd79eb8f0954d9d29d48059ab38853c7f79c582aa2653a16b4b9e176b0225 and i get the same error. here is my service at the frontend async function query() { try { // tried both this: return await axios.get(`http://127.0.0.1:8000/api/${types.TODO_API}/`,{headers : config.headers}); // and this: return await axios.get(`http://127.0.0.1:8000/api/${types.TODO_API}/`, null, {headers : config.headers}); } catch (err) { throw err; }; }; here is my setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'todo', 'user', 'knox' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'knox.auth.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } here is the TodoViewSet class TodoViewSet(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated, ) serializer_class = TodoSerializer def get_queryset(self): return self.request.user.todo.all() def preform_create(self, serializer): serializer.save(owner = self.request.user) here is the GetUserView class GetUserView(generics.RetrieveAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = UserSerializer def get_user(self): return self.request.user -
How to delete old profile picture when upload a new one - Django
I have a user profile page with profile picture based on ImageField in my model. When I submit the form and upload a new image the original image file isn't deleted from /static/images/. How can I delete the old profile picture from images folder after new picture was uploaded? -
Django background-tasks delay
I am having trouble with django background tasks. The tasks seems to work but there is no delay, the queued up tasks seems to be updating instantly, here is the code @background(queue='my-queue') def create_data(): # lookup user by id and send them a message temp = info(cam_name='webCam',cam_fps=webCam().get_fps()) temp.save() create_data(schedule=10,repeat=10) -
Rendering screenshots of urls in django [duplicate]
I want to create a django form in which I put the url and the screenshot/thumbnail of that url gets rendered below. Please tell me how to implement that ?? -
How to get data from models using date range picker and ajax in Django?
In HTML we have: <script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" /> <div id="reportrange" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc; width: 100%"> <i class="fa fa-calendar"></i>&nbsp; <span></span> <i class="fa fa-caret-down"></i> </div> <script type="text/javascript"> $(function() { var start = moment().subtract(29, 'days'); var end = moment(); function cb(start, end) { $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); } $('#reportrange').daterangepicker({ startDate: start, endDate: end, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] } }, cb); cb(start, end); }); </script> We need to get data from our models using ajax and date range picker, we want to show data according to report_date. Models.py: from django.db import models from django.db import connections class orders(models.Model): id = models.AutoField(primary_key=True) restaurant_id = models.IntegerField() driver_id = models.IntegerField() phone = models.CharField(max_length=20) report_date = models.DateTimeField(max_length=100, default=None, blank=True, null=True) We didn't find any working solution for it. Most were only using javascript function and not ajax. Would be nice to get some help with it. -
Creating Cascading drop downs using fields from another Model in Form Django
I am new to django and have been building some simple apps using foreign key and manytomanyfields however I now have a requirement at work and looking for some advise.. I have an existing table with 5 columns and each column has repetitive values except for the id column. ID | Category | Sub Category | Seller Now I want to create a new model where I want to use the unique values from category, subcategory and seller shown as drop downs in the form to save the selected values to the new model. Also, would it be easy to make them cascading drop downs on the form since they are coming from the same table. Please advise. Thanks for the advise. -
using select2 jquery with more than one form
I have a formset in django, I've used select2 for autocomplete, but it only work for the first form, wont affect others, I need to provide id forms dynamically! this my template //increase forms <script> $('#add_model').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('.model_formset').append($('#model_empty_formset').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> //my select2 <script> $(document).ready(function(){ $('#0model').select2() }) </script> <form method="POST">{% csrf_token %} {{ model.management_form }} {% for form in model.forms %} <div class="col-12 row mx-auto p-2 model_formset"> <div class="input-group inp mx-auto col-12 col-sm-10 p-1 col-md-5"> {{form.model_name | add_class:'col-12 text-center' | attr:'id:0model'}} </div> <div class="input-group mx-auto inp col-12 col-sm-10 p-1 col-md-5"> {{form.serial_number | add_class:'col-12 text-center'}} </div> </div> {% endfor %} <div id="model_empty_formset" class="col-12 row mx-auto p-2" style="display: none; border-top:1px solid white;border-radius: 30px;"> <hr class="col-10 bg-light"> <div class="input-group inp mx-auto col-12 col-sm-10 p-1 col-md-5"> {{model.empty_form.model_name | add_class:'col-12 text-center'}} {% if model.empty_form.model_name.errors %} <div class="error col-12 mx-auto"> {{model.model_name.errors }} </div> {% endif %} </div> <div class="input-group mx-auto inp col-12 col-sm-10 p-1 col-md-5"> {{model.empty_form.serial_number | add_class:'col-12 text-center'}} {% if model.empty_form.serial_number.errors %} <div class="error col-12 mx-auto"> {{pcmodel.serial_number.errors }} </div> {% endif %} </div> </div> <div class="col-12 col-sm-7 col-md-3 mx-auto"> <button class=" btn-block mt-1 shadow-lg border-right border-left">insert</button> </div> </form> How can I replace 0 in 0model with form id? -
Command 01_migrate failed on Amazon Linux 2 AMI
I have a Django project which is deployed to Elastic Beanstalk Amazon Linux 2 AMI. I installed PyMySQL for connecting to the db and i added these lines to settings.py such as below; import pymysql pymysql.version_info = (1, 4, 6, "final", 0) pymysql.install_as_MySQLdb() And also i have a .config file for migrating the db; container_commands: 01_migrate: command: "django-admin.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: mysite.settings Normally, i was using mysqlclient on my Linux AMI with this .config file but it doesn't work on Linux 2 AMI so i installed the PyMySQL. Now, i'm trying to deploy the updated version of my project but i'm getting an error such as below; Traceback (most recent call last): File "/opt/aws/bin/cfn-init", line 171, in <module> worklog.build(metadata, configSets) File "/usr/lib/python2.7/site-packages/cfnbootstrap/construction.py", line 129, in build Contractor(metadata).build(configSets, self) File "/usr/lib/python2.7/site-packages/cfnbootstrap/construction.py", line 530, in build self.run_config(config, worklog) File "/usr/lib/python2.7/site-packages/cfnbootstrap/construction.py", line 542, in run_config CloudFormationCarpenter(config, self._auth_config).build(worklog) File "/usr/lib/python2.7/site-packages/cfnbootstrap/construction.py", line 260, in build changes['commands'] = CommandTool().apply(self._config.commands) File "/usr/lib/python2.7/site-packages/cfnbootstrap/command_tool.py", line 117, in apply raise ToolError(u"Command %s failed" % name) ToolError: Command 01_migrate failed How can i fix this issue? -
Could not convert string to float:True
pay_rate = request.POST.get('pay_rate') charge_rate = request.POST.get('charge_rate') rate = request.POST.get('is_day_rate', False) Rates.objects.create(pay_rate=pay_rate, charge_rate=charge_rate,is_day_rate=rate) Error: could not string to float -
how do I develop django test cases for these 2 function based views?
I am new to making tests in django and wanted to ask how would test cases be for the below 2 FBVs. def add(request): data = {'success': False} if request.method=='POST': product = request.POST.get('product') user = request.user splitted = product.split(' ') sub_product = Product.objects.get(pk=(splitted[1])) original_product = Product.objects.get(pk=(splitted[0])) p = SavedProduct(username= user, sub_product=sub_product, original_product = original_product) p.save() data['success'] = True return JsonResponse(data) def delete(request): data = {'success': False} if request.method=='POST': product = request.POST.get('product') SavedProduct.objects.filter(pk=product).delete() data['success'] = True return JsonResponse(data) -
how to customize many to many field in the Django admin page?
I have 3 modules: Category: name = models.CharField(max_length=120,default='no name') Product: name = models.CharField(max_length=120, default='no name') image = models.ImageField(upload_to=settings.MEDIA_ROOT) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=None) and an Albom: name = models.CharField(max_length=120) products = models.ManyToManyField(to=Product) when I edit an albom throth the admin page it looks like this: I want to show not only the __str__ in the products horizontal_filter but allso the category and even filter by category. Is it possible? and if so, how would I do somthing like this? Thank you! -
Django, Security in Token authentication without CSRF token
I am using token authentication in Django project (removed session authentication) and it does't require CSRF token to communicate with server. Does this method compromises Django's default security features ? -
Python string to array : TypeError: iteration over a 0-d array
I have a string from a field in a query set which looks like this: [{'thirdParty': 'Funds Transfer'}, {'category': 'External Transfers'}, {'creditDebit': 'credit'}] I want to be able to loop through the elements in orther to be able to get {'thirdParty': 'Funds Transfer'} {'category': 'External Transfers'} {'creditDebit': 'credit'} And also to be able to loop through the keys of that object I am trying the following but I keep getting an error: TypeError: iteration over a 0-d array import numpy as np tags = "[{'thirdParty': 'Funds Transfer'}, {'category': 'External Transfers'}, {'creditDebit': 'credit'}]" arr = list(np.array(tags)) # print(type(tags)) # <class 'numpy.ndarray'> # print(tags) # [{'thirdParty': 'Funds Transfer'}, {'category': 'External Transfers'}, {'creditDebit': 'credit'}] for d in arr: print(d) -
How to display two date differences in year and months?
This code returns difference between two dates like this 0.4876712328767123 5.933333333333334 but what I want it in a human readable format. If the difference between two date is less than 1 year than I want to display only months like 5 months and if the difference is more than 1 year then I want result like 1 year 6 months . How can I do it? class MyModel(models.Model): start_date = models.DateField() end_date = models.DateField(blank=True, null=True) @property def date_period(self): if not self.end_date: self.end_date = timezone.now().date() period = self.end_date - self.start_date return '{0} {1}'.format(period.days/365, period.days/30) -
How can I get count of post with django
I wanted to get help with this django project. I'm trying to get the number of posts. def newQuestion(request): template = 'ask_question.html' form = askQuestion(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect("/") else: form = askQuestion() context = { 'form': form } return render(request, template, context) -
Django - Manipulate the url before it starts loading
I want to remove a part of the existing url of my Website when a user clicks a button. I have an anchor inside a button, but I want to get rid of that to be able to manipulate default url in javascript click handler. Here is my code <tbody> {% for stu in st %} <tr> <td> {{stu.id}} </td> <td> {{stu.type}} </td> <td> {{stu.detail}} </td> <td> {{ stu.title }} </td> <td class="td-actions"> <span class="row mb-3" style="width:8vh;"> // I know it's wrong to have an anchor inside a button, but how to do that with javascript click handler <button class="btn" type="button" id="edit_btn" title="Edit" style="color:white;background-color:#fff;"> <a href="/data/{{stu.id}}/update"> <i class="glyphicon glyphicon-pencil fa-2x"></i> </a> </button> <button class="btn" type="button" id="dlt_btn" title="Delete" style="color:white;background-color:#fff;"> <a href="/data/{{stu.id}}/delete"> <i class="glyphicon glyphicon-trash fa-2x"></i> </a> </button> </span> </td> </tr> {% endfor %} </tbody> ... ... ... <script> var editBtn= document.getElementById('edit_btn'); editBtn.addEventListener("click",function(){ //Here I need {{stu.id}} because I want to remove some part from the default utl before directing to /data/{{stu.id}}/update }) </script> -
in Django I am trying to add a user object to a manytomany field, but it keeps adding all the users objects
in my model.py: class Vote(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Product(models.Model): title = models.CharField(max_length=255) votes_total = models.ManyToManyField(Vote, related_name="votes", blank=True) in my view.py: def create(request): if request.method == 'POST': product = Product() product.title = request.POST['title'] vote.user = request.user vote.save() product.save() product.votes_total.add(vote) product.save() So after I create a user and go to the admin page. under votes_total it has added all of the vote objects that have been created. I just want the user vote added. I am not sure why it adds all of the votes that have ever been created admin/product Product(1) -> votes_total = {voteObject(1),voteObject(2),voteObject(3),...} I just want the current voteobject i sent added for that created product Product(1) -> votes_total = {voteObject(1)} I thought i have a clear understanding of it but anyone know where I went wrong? -
Django: Calling images in gallery using database?
I am calling images from a model in database in django like this: {% for pet in pets %} {{pet.name}} {{pet.desc}} {% if pet.avail %} Available! {% else %} Already adopted :) {% endif %} {% endfor %} And then I want to call any one of the images that will be clicked into a modal(which I outside the for loop) which the js file with collect the image URL and pass it to the main class: Hello! But when the code runs, the image class "fs-gal-main" comes up with an unknown source. What do I do? -
Model with field relationship to user account, field not showing up in django admin
I have a simple model where I have added in a field to link to django usernames, based on this answer. My model: class Customer(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) customer_email = models.EmailField(max_length = 254) username = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) My model shows up in django-admin panel fine, but the username field does not show up. I was expecting a dropdown to be able to assign a user from existing users, or at least a text field. How can I assign a user to a record in my model? -
Flask to Django conversion
Flask project html code <a href="{{ url_for('flight', flight_id=flight.id) }}"> python code @app.route("/flights/<int:flight_id>") def flight(flight_id): I want to convert the above piece of code into corresponding Django form. Inside Django project in views.py file def flight(request) is defined. -
I want to read the values from one textarea and pass the same values to another textarea in django?
I want to user input column-wise value in textarea and then clicking on a button/running the code (button click code not done yet) the value in textarea will pass to another textarea. I sucessufully did with textbox, but it is not working for text area. Please guide me here (I want to do this in Django). <pre> **Index.html code:** {% block content %} <!doctype html> <html> <head> <title>Register</title> </head> <body> <h1></h1> <form action="one" method = "post"> {%csrf_token %} <input type="text" name ="text"><br> <input type="Submit"> </form> </body> </html> {% endblock %} </pre> <pre>**Views.py code:** from django.shortcuts import render,redirect import cgi,cgitb # Create your views here. def index(request): return render(request,"index.html") def one(request): form = cgi.FieldStorage() user = form.getvalue("text") return render(request,"one.html",{"user":user}) </pre> <pre>**One.html** {% block content %} <Html> <body> {%csrf_token %} <input type = "text" value = {{user}}> <h2>{{user}}</h2> <h2>{{user}}</h2> </body> </Html> {% endblock %} </pre> -
Load external (absolute) URL in urlpatterns
I want to associate my URL patterns in Django with an external URL. Something like: urlpatterns += [ path("https://google.com/", include("site.urls")), ] This work. However, when I generate my URLS like so: <a href="{% url "somepage" %}">link</a> Then it leads to: <a href="/https://google.com/record/">link</a> In other words, there is a slash in front of the URL generated. How can I get rid of that one? -
Datetime dictionary group by Date Key
I have been heavily customizing an admin.py page where it shows the history of a user accessing specific endpoints. My client, however, wants me to group this list by date. The list is also the work of my customization. Let me show you what I mean. class UserAdmin(BaseUserAdmin): form = UserChangeForm add_form = UserCreationForm list_display = ('email', 'level', 'is_admin', 'is_active', 'user_counts') def user_counts(self, x): return x.counts.count() list_filter = ('is_admin',) fieldsets = ( (None, {'fields': ('email', 'password',)}), ('Personal info', {'fields': ('level',)}), ('Permissions', {'fields': ('is_admin', 'is_active',)}), (None, {'fields': ['user_counts_detail']}), ) readonly_fields = ['user_counts_detail'] def user_counts_detail(self, x): visits = [{"id": a.id, "date": a.date_time.date().strftime("%Y-%M-%d"), "time": a.date_time.time().strftime("%H:%M:%S") } for a in x.counts.all()] return visits Here the 'visits' list contains the id and the date and the exact time of each visit. However, the list is not as organized and can be a bit cryptic for non-developers. Below is the screenshot of the admin page. My question is: Is there anyway I can group such dictionaries by "date" key? I tried to find a way to do grouping in list comprehension but I failed to find any way to do this. Thanks a lot in advance! -
I need all data in a model on a excel sheet Django
I am creating a api,i which i want all data on a excel sheet class Task(models.Model): name=models.CharField(max_length=20) address=models.CharField(max_length=50) def __str__(self): return str(self.name) #viewset plan=Task.objects.all() b=[] for i in plan: b.append({ "name":i.name, "address":i.address, }) return Response({"data":b}) output should be 0 name:address 1 Ashu:Gurgaon -
Form not saving to datebase
I have two models order and date. I have created a date form that saves entered date values to an Order model foreign key field. My form was working fine before, it was creating a new date object in the admin database. After adding js to create a pop up window form , my date form has stopped working. views.py def dateDetailView(request, pk): order = Order.objects.get(pk=pk) date_instance = order.date form = DateForm(request.POST or None, request.FILES or None, instance=date_instance) if request.method == 'POST': if form.is_valid(): date_instance = form.save() order.date = date_instance order.save() else: form = DateForm() y_form = render_to_string('date_list.html',{'form':form,'order':order}, request=request, ) return JsonResponse({'y_form': y_form}) forms.py class DateForm(ModelForm): class Meta: model = Date widgets = {'date_added': DateInput(),'scheduled_date': DateInput(),'service_period':DateInput(),'modified_date':DateInput(), 'finish_date':DateInput()} fields = '__all__' date_list.html {% load static %} {% load crispy_forms_tags %} {% load widget_tweaks %} {% block content %} <!DOCTYPE html> <html> <head> <title> </title> </head> <body> {% if request.user.is_superuser %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">Date List</h4> </div> <center> <form class="" action="" method="POST"> {% csrf_token %} <div class="modal-body"> {{form|crispy}} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-dark">Update</button> </div> </form> {% endif %} {% endblock %}