Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Recursive query in Django
Models.py from django.db import models from django.contrib.auth.models import User class EmployeeRelation(models.Model): employee = models.ForeignKey(User, on_delete=models.CASCADE, related_name='hierarchy_user') reporting_to = models.ForeignKey(User, on_delete=models.CASCADE, related_name='hierarchy_manager') class SalesLines(models.Model): rep = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sale_user') reporting_day = models.DateField() revenue = models.DecimalField(max_digits=16, decimal_places=4) Views.py from django.http import JsonResponse from typing import List, Union from django.db.models import Sum, Q from .models import EmployeeRelation, SalesLines def get_revenue_by_sales_rep(request, user_id): employeeObj = EmployeeRelation.objects.filter(reporting_to_id=user_id) data = {} if employeeObj: for subject in employeeObj: # the current user is a subject and has managers under him. managerSet = EmployeeRelation.objects.filter(reporting_to_id=int(subject.employee_id)) # if the person below is also a manager if managerSet: for salesrep in managerSet: temp = {} temp = get_revenue_sum(salesrep.employee.id) data = {**data,**temp} else: temp = {} temp = get_revenue_sum(subject.employee.id) data = {**data,**temp} else: data = get_revenue_sum(user_id) return JsonResponse({"revenue": data}) def get_revenue_sum(salesrep_id): salesRepObj = EmployeeRelation.objects.get(employee_id=salesrep_id) full_name = salesRepObj.employee.get_full_name() revenue = "{:.2f}".format(SalesLines.objects.filter(rep_id=salesrep_id).aggregate(Sum('revenue'))['revenue__sum']) return {full_name:revenue} I'm trying to get the revenue of sales rep that works under every user. So a user can be a director, manager, or sales rep. So for instance, if there is a director and a manager works under him then I need to recursively find the revenue of all the sales rep that works under the manager and so on. My … -
Django Horizontal Scroll on Top of Changelist
I have the same problem as depicted here by mozman2: "In my Django changelist there are lots of columns that means there is a scrollbar at the bottom of the list. Is it possible to get a scrollbar to appear at the top so I don't need to scroll down" The solution from the given link seemed to help mozman2. However, I cannot reproduce it. Hence I tried copy-pasting the code from https://github.com/avianey/jqDoubleScroll#readme In particular, I copied this file from the repository to MyApp/static/admin/js/ jquery.doubleScroll.js The file looks like this: /* * @name DoubleScroll * @desc displays scroll bar on top and on the bottom of the div * @requires jQuery * * @author Pawel Suwala - http://suwala.eu/ * @author Antoine Vianey - http://www.astek.fr/ * @version 0.5 (11-11-2015) * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Usage: * https://github.com/avianey/jqDoubleScroll */ (function( $ ) { jQuery.fn.doubleScroll = function(userOptions) { // Default options var options = { contentElement: undefined, // Widest element, if not specified first child element will be used scrollCss: { 'overflow-x': 'auto', 'overflow-y': 'hidden', 'height': '20px' }, contentCss: { 'overflow-x': 'auto', 'overflow-y': 'hidden' }, onlyIfScroll: true, // top scrollbar is not … -
How to estabalish ManyToMany relationship on instantiation of object through generic CreateView?
So I have two models. Deck and Card. When the user creates card it should be tied to a deck, in a ManyToMany relationship. The card is created through the Generic Django create view, and I can't crack how I can assign the card to a deck, in this context. Any ideas on how I might solve this? My CreateView class CardCreateView(LoginRequiredMixin, CreateView): model = Card fields = ['question', 'answer'] def form_valid(self, form): form.instance.creator = self.request.user return super().form_valid(form) def get_success_url(self): return reverse('spaced_repitition-home') def assign_card(self, deck_id): #It's largely this part where I don't understand that it doesn't work card = self.get_object() deck = get_object_or_404(Deck, pk=deck_id) card.decks.add(deck) card.save() Template that sends user to form (passes on deck_id) {% for deck in decks reversed %} <a href="{% url 'card-create' deck_id=deck.id %}"> <p> Add Card </> {% endfor %} Form Template {% extends "spaced_repitition/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class=form-group> <legend class="borders-bottom mb-4"> Create Card </legend> {{ form|crispy }} <div class=form-group> <button class= "btn btn-outline-info" type="submit"> Create </button> </div> </fieldset> </form> {% endblock content %} Models class Deck(models.Model): title = models.CharField(max_length=100) date = models.DateTimeField(default=timezone.now) creator = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField(max_length=200, blank=True) … -
RenderItems is not defined no-undef inside return
Hello Guys am new in reactjs and Iam trying to get response data object to be able to display on the webapp for the users to see instead of them inspecting the page and going to network/console to see the file upload error response of name= 'title' so I decided to use the function below to be able to give me the data response and I keep on getting this error 'renderItems is not defined' no-undef Heres the sample code: import React from "react"; import PropTypes from "prop-types"; import axios from 'axios' import { Card,} from "shards-react"; class Uploaddatastore extends React.Component { constructor(props) { super(props); this.state = { UploadNotification: [] } } componentDidMount(){ let notificationComponent = this; axios.get("http://127.0.0:8000/uploads/file_upload/") .then(function (response) { console.log(response); console.log(response.data); notificationComponent.setState({ UploadNotification: response.data.items }); }) .catch(function (error) { console.log(error); }); } render() { if (this.state.UploadNotification.length) { let renderItems = this.state.UploadNotification.map(function(item, i) { return <li key={i}>{item.title}</li> }); } return ( <div> <span className="text-danger"> {renderItems} </span> </div> ); } }; export default Uploaddatastore; -
Not able to serialize a model object in django signals
I have a Task model. After saving the task I want to send a FCM to a device. So I decided to use django signals. Here's the code for it: The model: class Task(models.Model): id = models.AutoField(primary_key=True) issuer = models.ForeignKey(EndUser, on_delete=models.CASCADE, related_name='history') assignee = models.ForeignKey(Mechanic, on_delete=models.CASCADE, related_name='history') vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, related_name='history') service = models.ForeignKey(Service, on_delete=models.CASCADE) status = models.CharField('Task Status', choices=TASK_STATUS, default=TASK_STATUS[0][0], max_length=64) payment_status = models.CharField('Payment Status', choices=PAYMENT_STATUS, default=PAYMENT_STATUS[0][0], max_length=64) def __str__(self): return "{}-{}-{}".format(self.service, self.issuer, self.assignee) post_save.connect(send_mechanic_notification, sender=Task) The signal function: def send_mechanic_notification(sender, instance, created, **kwargs): if created: instance.assignee.device.send_message( title='New Task Available!', body='Hey!! A new task is available for you', data={ "event": "new_task", "data": instance } ) Now, obviously this won't work because instance is a model object and needs to be serialized. So I tried using a serializer that I have defined. But this was causing circular dependency. I don't want to user model_to_dict because it doesn't serialize the nested fields, and serializing the nested fields is a requirement. How can I solve this problem? -
Django 2.2 how do i list objects with a many to many in a template?
Hi all, I have seen similar questions to this. However the answers don't print anything out in my code. Can someone help with the below? I am trying to list some products and should display the appropriate text, depending on whether they are in the cart. "In cart", "add to cart". The models I have are: class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) image = models.ImageField(upload_to='products/', null=True, blank=True) featured = models.BooleanField(default=False) quantity = models.IntegerField(default=0) active = models.BooleanField(default=True) is_digital = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class CartItem(models.Model): product = models.ForeignKey(Product, default=None, null=True, blank=True, on_delete=models.CASCADE) quantity = models.IntegerField(default=None, null=True) price_of_item = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) session_id = models.CharField(max_length=120, default=0, null=True, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) def __str__(self): return str(self.id) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) cart_items = models.ManyToManyField(CartItem, default=None, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) In list.html I list all the products available: {% if product_list %} <div class="row"> {% for product in product_list %} <div class='col-sm-12 col-md-4 col-lg-4 my-2'> {% include 'products/snippets/card.html' with product_obj=product %} <br> </div> {% endfor %} </div> … -
CeleryD seems to ignore concurrency arguemtn
I've recently upgraded my Django project to Celery 4.4.6 and things aren't going well. My current number one problem is the concurrency of tasks. Because the tasks lock database tables and some are very memory intensive, there's no chance to run eight tasks at the same time. However, that is what celery is set on doing. Previously I was able to run just two tasks at the same time. The worker is daemonised and only one worker is live (one node). I set the concurrency to two. Here's my /etc/default/celeryd: # most people will only start one node: CELERYD_NODES="worker1" # but you can also start multiple and configure settings # for each in CELERYD_OPTS #CELERYD_NODES="worker1 worker2 worker3" # alternatively, you can specify the number of nodes to start: #CELERYD_NODES=3 # Absolute or relative path to the 'celery' command: CELERY_BIN="/home/ubuntu/dev/bin/python -m celery" #CELERY_BIN="/virtualenvs/def/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="match2" # or fully qualified: #CELERY_APP="proj.tasks:app" # Where to chdir at start. export DJANGO_SETTINGS_MODULE="match2.settings" CELERYD_CHDIR="/home/ubuntu/dev/match2/match2" # Extra command-line arguments to the worker CELERYD_OPTS="--concurrency=2" # Configure node-specific settings by appending node name to arguments: #CELERYD_OPTS="--time-limit=300 -c 8 -c:worker2 4 -c:worker3 2 -Ofair:worker1" # … -
Auto Increment field with starting value in Django
I am creating a model given below. I want the student id to start from 100000. class StudentLogin(models.Model): student_id = models.AutoField(min_value = 100000) email = models.EmailField(max_length=200) password = models.CharField(max_length=255) I am getting the following error if I use min_value TypeError: __init__() got an unexpected keyword argument 'min_value' -
UserProfileInfoForm' object is not callable
''' views.py from django.shortcuts import render from practise.forms import UserForm, UserProfileInfoForm def index(request): return render(request, 'index.html') def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request, 'registration.html', {'user_form': user_form, 'profile_form': profile_form, 'resigtered': registered}) ''' '''' error Internal Server Error: /index/register/ Traceback (most recent call last): File "C:\Users\Faris\PycharmProjects\djangoProject4\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Faris\PycharmProjects\djangoProject4\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Faris\PycharmProjects\djangoProject4\practise\views.py", line 22, in register profile = profile_form(commit=False) TypeError: 'UserProfileInfoForm' object is not callable [19/Aug/2020 21:05:57] "POST /index/register/ HTTP/1.1" 500 68871 '''' -
Django Form- Password Validation
I am new to Django just started learning it yesterday. I am trying to create a register form. I know there is inbuilt django register system. But i am trying to it myself. This is my Views.py- def register(request): if request.user.is_authenticated: return render(request, 'users.html', {}) else: if (request.method=='POST'): form=Register(request.POST) if form.is_valid(): form.save() return render(request,'home.html',{}) else: return render(request,'register.html', {}) Template- <form method="post"> {% csrf_token %} <input type="text" name="username" placeholder="Username" required><br> <input type="email" name="username" placeholder="Email" required><br> <input type="password" placeholder="Password" name="password" required><br> <input type="password" placeholder="Password" name="cpassword" required><br> <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="female">Female<br> <input type="submit"> form.py class Register(forms.ModelForm): class Meta: model = Users fields = ["username", "email", "password","gender"] But since there is no confirm password field in form.py. It does not past form.is_valid() statement. I know this may be a stupid. But just can't find a way to do this. -
How to test which EMAIL credentials were used in tests
I am building an application that sends email through multiple email servers. To achieve this, I created my own settings that allow for multiple email server configurations. Now I am testing and I want to ensure the method is inserting the correct credentials. I looked at the django.core.mail and there does not appear to be anything there. Is there a way to test which credentials were used when testing email sending? -
Django channels, time a message in a websocket
I want to implement a WebSocket which execute a queryset every 120 seconds and returns a response in according to some logic (already exsits) class CarConsumer(JsonWebsocketConsumer): def connect(self): # Manually adding a user for now, later from the url route. self.user_name = '1' self.user_group_name = 'user_%s' % self.user_name self.group = [self.user_group_name, self.channel_name] # Join user group async_to_sync(self.channel_layer.group_add)( self.group[0], self.group[1] ) # TODO: Once working, add Auth # accept connection self.accept() def car(self): result = self.check_events() # Get updated car status self.channel_layer.send( self.farm_group_name, # send result to group {'type': 'check_events', 'message': result } ) def check_events(self): Car.objects.filter() # rest of logic cut dows due to length. So, this code connects when using: const ws = new WebSocket("ws://127.0.0.1:8000/ws/car_online/connect/"); a connection is established, but I can't seem to be able to send a proper message, and other then that, I want the check_events method (the logic) to run every 120 seconds, how can I implement this behavior? The result of the check events method is always a dictionary if it changes something. -
Django graphql-jwt refresh token - Invalid object name 'refresh_token_refreshtoken'
I used to work on this application on a different machine. I fetch the app from Git installed all dependencies and migrated my database (I am using MS Sql Server). when i tried to authenticate i got this error: django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'refresh_token_refreshtoken'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") I don't know what happened wrong. and if this object should be created with the migrations. -
Django models: how to get an model object in my views
So I have this models class ThreadManager(models.Manager): def by_user(self, user): qlookup = Q(first=user) | Q(second=user) qlookup2 = Q(first=user) & Q(second=user) qs = self.get_queryset().filter(qlookup).exclude(qlookup2).distinct() return qs def get_or_new(self, user, other_username): # get_or_create username = user.username if username == other_username: return None qlookup1 = Q(first__username=username) & Q(second__username=other_username) qlookup2 = Q(first__username=other_username) & Q(second__username=username) qs = self.get_queryset().filter(qlookup1 | qlookup2).distinct() if qs.count() == 1: return qs.first(), False elif qs.count() > 1: return qs.order_by('timestamp').first(), False else: Klass = user.__class__ user2 = Klass.objects.get(username=other_username) if user != user2: obj = self.model( first=user, second=user2 ) obj.save() return obj, True return None, False class Thread(models.Model): first = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_first') second = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_second') updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) thread_notification = models.IntegerField(default=0) objects = ThreadManager() in my model Thread I want to get the object thread_notifications, so I make my views like this def new_notification_thread(request): thread_notifier = Thread.objects.filter(pk=1) thread_notifier.thread_notification += 1 thread_notifier.save() return JsonResponse(serializers.serialize('json', [thread_notifier]), safe=False) The problem is that when I run my code I get Thread matching query does not exist. does anybody know what is going on? -
FileNotFoundError at /analyze/info/ [Errno 2] No such file or directory: '/media/test2_SjHB3FP.jpg'
I am new to Django. I am trying to upload the image and use that image in a view.py function as well show in index.html. Below are the steps I performed but getting error as "No such file or directory". I feel like I am doing some mistake to the path which I have provided in it, But I'm not sure where I am doing wrong. #Settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' after creating this MEDIA_URL I pass this into the urls.py of the root folder: #root\urls.py urlpatterns = [ path('admin/', admin.site.urls), path('xxxxx/', include('xxxx.urls')) ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) then i created application\model.py: #application\model.py from django.db import models class history(models.Model): url = models.CharField(max_length=200) data = models.CharField(max_length=2500) now application\urls.py: #application\urls.py urlpatterns = [ path('', views.index, name='index'), path('info/', views.info, name='info'), path('history/', views.getHistory, name='history'), ] Now this is my application\views.py: def info(request): os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'bd5f7e5a.json' client = vision.ImageAnnotatorClient() myfile = request.FILES['pic'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) file_name = fs.url(filename) with io.open(file_name, 'rb') as image_file: # at this line I am getting the error that no such file found #********function goes here ********* return render(request, 'results.html', {"labels":doctext, 'image': file_name}) Now check my index.html file: <body > <form action='/analyze/info/' method='post' class="form" enctype="multipart/form-data"> {% csrf_token %} … -
how can I filter the difference between the two models? using django
I have 2 models, Product and ProductRelatedGroupAndProduct , the Product have 5 data, [chicken, okra, ampalaya, cabbage, carrots] and the ProductRelatedGroupAndProduct have [chicken, okra, cabbage] how do i get the remaining data in Product that dont have in ProductRelatedGroupAndProduct ? the choosen product is ProductRelatedGroupAndProduct and the list of product is Product I just want that the data displayed on the choosen product should no longer be visible in the product list. so far this is my views.py def searchrelatedproduct(request): id = request.GET.get('relatedproductID') products = Product.objects.all() relatedproduct = ProductRelatedGroupAndProduct.objects.filter(productrelatedgroup = id) return render(request, "customAdmin/relatedproduct.html",{"products":products,"relatedproduct":relatedproduct}) this is my html <div class="container"> <form method="POST" action="/GroupOfProduct/" enctype="multipart/form-data">{% csrf_token %} <h2>Product </h2> <div class="form-group"> <br> <label for="sel2">List Of Products</label> <select multiple class="form-control" id="sel2" name="product"> {% for product in products %} <option>{{product.product}}</option> {% endfor %} </select> </div> <input type="submit" style="float:right;"> </form> </div> <div class="container"> <h2>Choosen Product</h2> <form method="POST" action="/UpdateGroupOfProduct/" enctype="multipart/form-data">{% csrf_token %} <input type="submit" style="float:right;"> <div class="form-group"> <br> <label for="sel2">List Of Choosen Products</label> <select multiple class="form-control" id="sel2" name="relatedproduct"> {% for product in relatedproduct %} <option value="{{ product.id }}">{{product.product}}</option> {% endfor %} </select> </div> </form> </div> -
Elasticsearch document fields type index automatically changes
I'm working on a project containing django, elasticsearch and django-elasticsearch-dsl. I'm collecting a quite large ammount of data and saving it to postgres and indexing it to elasticsearch, via django-elasticsearch-dsl. Im bumping into a problem I dont understant, nor do I have any further hints what happens: Relevant part of Django's models.py file: class LinkDenorm(BaseModel): ... link = CharField(null=True, max_length=2710, db_index=True) link_expanded = TextField(null=True, db_index=True) title = TextField(null=True, db_index=True) text = TextField(null=True) ... Relevant part of django-elasticsearch-dsl documents.py file: @registry.register_document class LinkDenorm(Document): link_expanded = fields.KeywordField(attr='link_expanded') class Index: name = 'denorms_v10' class Django: model = models.LinkDenorm fields = [ ... 'link', 'title', 'text', ... ] After data is successfully indexed, I verify that the index is containing the correct fields: curl -X GET -u <myuser>:<mypasswd> "http://<my-hostname>/denorms_v10/?pretty" { "denorms_v10" : { "mappings" : { "properties" : { ... "link" : { "type" : "text" }, "title" : { "type" : "text" }, "text" : { "type" : "text" } "link_expanded" : { "type" : "keyword" }, ... } } } } After a certain ammount of time (sometimes weeks, sometimes days) the index fields are changed. Executing the same CURL lookup as before gives me: curl -X GET -u <myuser>:<mypasswd> "http://<my-hostname>/denorms_v10/?pretty" { … -
Django dynamic form for call of roll
I need to create a form with django to check if students are prensent or not. I can't use the 'normal' way to create a form because django want a form model implemented with every fields composing the form. I can't do this cause i don't know the number of students in a class. how can i create a dynamic form who don't care about the number of students ? at the moemnt i created a form in the template with a for to showthe list of students with each checkbox <form method="post"> {% csrf_token %} Date : <input id="date" type="date" class="mt-3 mb-3"> <br> {% for student in student_list %} <input type="checkbox" id="student{{forloop.counter}}" name="student{{forloop.counter}}"> <label for="student{{forloop.counter}}">{{student.first_name }} {{student.last_name}}</label> <br> {% endfor %} <button class="btn btn-outline-primary mr-4"><a href="/lycee/">Cancel</a></button> <button type="submit" class="btn btn-success radius d-flex">Submit</button> </form> -
Inline css image reference in Django template
I passed context_object_name = 'project' in template and I need this: <div style="background-image: url( {{ project.thumbnail.url}} )"></div> but above line doesn't work. However, <img src="{{ project.thumbnail.url }}" alt="thumb" /> works fine. What is the solution? Thank you in advance -
Can I add Mayan EDMS to my existing Django web app?
I need a document management library to add to my existing web application. Can I add Mayan EDMS as a Django Application to my existing Django Web Application? I can't see any documentations regarding it online. -
Django - Is there a weekly calendar widget similar to when2meet.com?
I'm trying to create an application that allows a user to set a weekly schedule of when they would be available to meet. Once these set weekly schedules have been made, it would then be set to unavailable once a customer's proposal to meet is approved by the user. -
Django. Model not showing up in template
I'm making my first Django project, and I added a model in the template, but, when I'm running it, I don't see anything. but when I inspect the page, I see an h2 tag for each entry in the model. models.py from django.db import models from django.utils import timezone from django.urls import reverse class MyDate(models.Model): english_date = models.DateField(auto_now=False) hebrew_date = models.CharField(max_length=20) def __str__(self): return self.hebrew_date views.py from django.views.generic import (TemplateView,ListView,DetailView,CreateView,UpdateView,DeleteView) from luach.models import MyDate class HomePage(TemplateView): template_name = 'new.html' class MyDateListView(ListView): model = MyDate context_object_name = 'mydate' template {% extends 'luach/base.html' %} {% block content %} <div class="jumbotron"> {% for mydate in mydate %} <h2>Hi{{ MyDate.hebrew_date }}</h2> {% empty %} <h2>Sorry, no dates in this list.</h2> {% endfor %} </div> {% endblock %} -
React put method not updating the user from Django
I have a Django as backend and updating the user from postman is working fine. But when I update it via React Frontend, it replies with a success message just as in Postman, but the data was not updated. This is the update function to update: const updateData = (e) => { e.preventDefault(); const csrftoken = getCookie("csrf"); const cookies = new Cookies(); const url = "http://localhost:8000/usercontrol/update"; setIsLoading(true); fetch(url, { method: "PUT", headers: { "Content-Type": "application/x-www-form-urlencoded", Authorization: "Token " + cookies.get("token"), "X-CSRFToken": csrftoken, }, body: JSON.stringify({ email: userinfo.email, username: userinfo.username, first_name: userinfo.first_name, last_name: userinfo.last_name, }), }).then((response) => console.log("THE RESPONSE: ", response.json())); setIsLoading(false); }; This is what it prints out in the console Since I am partially following CodingWithMitch for Django user creation with rest framework is similar to his. Furthermore, since there is no error outputting and is working fine in Postman, I have no idea what is wrong with it. -
unresolved import 'rest_framework' after installing djangorestframework
I saw similar posts created before, but nothing helped me in the end. I am using Python 3.7.7 and my IDE is VSC. I installed pip install djangorestframework (both in my virtualenv and outside of it) Added 'rest_framework', to INSTALLED_APPS. Now, to used djangorestframework, I created a file serializer with from rest_framework import serializers Now, rest_framework becomes underlined with the message unresolved import 'rest_framework'. The whole app still works, there is no error in the console. What would you advise me to do? Thanks! -
Key error request in get_export_data lib django-import-export
I used this function for some time and for some reason I started getting the error: Key error request like a picture This is my code:(Error in line: data = e.get_export_data(XLSX(), queryset)) def _export_data(queryset, model, filename_prefix, resource_class): e = ExportMixin() e.resource_class = resource_class e.model = model data = e.get_export_data(XLSX(), queryset) content_type_ = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' response = HttpResponse(data, content_type=content_type_) out_format = 'attachment; filename="{0}-{1}.xlsx"'.format( slugify(filename_prefix), filename_suffix) response['Content-Disposition'] = out_format return response Obs: My lib version is 2.0.2