Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to paginate the filtered results in django
views.py def do_paginator(get_records_by_date,request): page = request.GET.get('page', 1) paginator = Paginator(get_records_by_date, 5) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return users def index(request): if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) new_records_check_box_status = request.POST.get("new_records", None) print(new_records_check_box_status) error_records_check_box_status = request.POST.get("error_records", None) print(error_records_check_box_status) drop_down_status = request.POST.get("field",None) print(drop_down_status) global get_records_by_date if new_records_check_box_status is None and error_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)) get_records_by_date = check_drop_down_status(get_records_by_date,drop_down_status) get_records_by_date = do_paginator(get_records_by_date,request) elif new_records_check_box_status and error_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(new_records__gt=0) get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status) get_records_by_date = do_paginator(get_records_by_date, request) elif error_records_check_box_status and new_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(error_records__gt=0) get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status) get_records_by_date = do_paginator(get_records_by_date, request) else: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(Q(new_records__gt=0)|Q(error_records__gt=0)) get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status) get_records_by_date = do_paginator(get_records_by_date,request) # print(get_records_by_date) else: roles = Scrapper.objects.all() page = request.GET.get('page', 1) paginator = Paginator(roles, 5) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, "home.html",{"users": users}) return render(request, "home.html", {"users": get_records_by_date}) home.html <!DOCTYPE html> <html> <body> <style> h2 {text-align: center;} </style> <h1>Facilgo Completed Jobs</h1> <div class="container"> <div class="row"> <div class="col-md-12"> <h2>Summary Details</h2> <table id="bootstrapdatatable" class="table table-striped table-bordered" width="100%"> <thead> <tr> <th>scrapper_id</th> <th>scrapper_jobs_log_id</th> <th>external_job_source_id</th> <th>start_time</th> … -
Does rows exists in pivot table
Is there a cleaner way to check does all providers for item exists in pivot table? eg. I have few items, if one of them has all given providers then method should return True otherwise False for item in items: exists_count = 0 for provider in providers: if ItemProviderConn.objects.filter( item_id=item.pk, provider_id=provider.pk, ): exists_count += 1 else: break if exists_count == len(providers): return True return False -
The difference between create() method and create_user() in Django
I created the user model myself and I don't use Django's default model. To create a user, if I use the create() method, the date field will set value that field, but if I use the create_user() method, I have to give a value to the date field. Why does this happen? class UserManager(BaseUserManager): def create_user(self, email, f_name, l_name, phone, create, password): user = self.model(email=self.normalize_email(email), f_name=f_name, l_name=l_name, phone=phone, create=create, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, f_name, l_name, phone, create, password): user = self.create_user(email, f_name, l_name, phone, create, password) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): f_name = models.CharField(max_length=50) l_name = models.CharField(max_length=50, blank=True, null=True, ) email = models.EmailField(unique=True, blank=True, null=True) phone = models.BigIntegerField(blank=True, null=True, ) data = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) permission = models.ManyToManyField(Permission, related_name='users') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['phone', 'f_name', 'l_name', 'create'] objects = UserManager() -
Django, additional fields by product category
Please help. I'm trying to write an online store in Django. I want additional fields of product characteristics to appear depending on the product category. For example: if you select the "coffee" category in the admin panel when creating a product card, then a block with additional fields would appear: processing_method, geography, special, sour, roasting. If you select the category "tea" - there are other additional fields. I tried using fieldsets in admin.py - I realized that this option is not suitable. I stopped at creating a field in models.py - characteristics = models.JSONField(), read the documentation and did not understand how to implement my case. The meaning of the ideas is in the dynamic formation of the card (additional fields) when choosing a category I will be glad to any link with a similar example or a solution to a similar problem or guidance on the right way to solve this problem. models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class Product(models.Model): ROASTING_CHOICES = ( (1, 1), (2, 2), (3, 3), (4, 4), (5, 5) ) … -
You do not have permission to perform this action Even if i dont put any permession class on the view
my setting.py authentication setting for drf REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } my views which having issu @api_view(['POST']) @permission_classes([IsAuthenticated]) def createAddress(request): data = request.data try: address = AddressSerializer(data=data) if address.is_valid(): address.save() return Response(address.data) else: return Response(address.errors, status=status.HTTP_400_BAD_REQUEST) except Exception: message = {'detail': 'Address is not valid'} return Response(message, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET']) @permission_classes([IsAuthenticated]) def getAddress(request): print(request) address = Address.objects.all() serializer = AddressSerializer(address, many=True) return Response(serializer.data) When i hit createAddress with Autherization in the header and the Token as well in that works fine but when i hit getAddress then i get the error Even if i comment the permission class on the getAddress i still get the issue -
React + Django csv handle
I'm working on a Data Mining app with React and Django, I kind of understand how to send the file to Django, but how do I read the file, apply an algorithm and return the process data to react for showing it? The objective of the app is to read a differente csv file each time, so, I don't need to create models, don't even need to store the data, just handle the information. I've seen a lot of tutorials, but everyone make use of a database, is there a method to process the file without saving anything, just processing and return the process data for create graphs and stuff? how an I do that? This is my attempt with a react component for sending the file to django, but now, whats next? how do I read it in django? and how do I send the process data back to react? import { useState } from "react"; function DragDropFiles(){ const [selectedFile, setSelectedFile] = useState(); const [isFilePicked, setIsFilePicked] = useState(false); const changeHandler = (event) => { setSelectedFile(event.target.files[0]); setIsFilePicked(true); } const handleSubmission = async () =>{ const formData = new FormData(); formData.append('File', selectedFile); let newData = await fetch( base_url, { method: 'POST', … -
Django: Object not getting serialized as Object but instead shows Foreign Key [closed]
I've been trying to display an object "pfam" within another object "domains". But the results I'm getting shows pfam_id just as a foreign key. I've tried printing the details of queryset and queryset[0].pfam gets me a pfam object so I know my models isn't wrong. I'm thinking its something to do with the serializers but I'm not too sure what went wrong. Models.py imports .. class pFam(models.Model): domain_id = models.CharField(max_length=256,null=False,blank=False,unique=True) domain_description = models.CharField(max_length=256,null=False,blank=False) class Domains(models.Model): pfam = models.ForeignKey(pFam,on_delete=models.CASCADE) description = models.CharField(max_length=256,null=False,blank=False) start = models.IntegerField(null=False,blank=False) stop = models.IntegerField(null=False,blank=False) Serializer.py imports .. class PfamSerializer(serializers.ModelSerializer): class Meta: model = pFam fields = ['domain_id','domain_description'] class DomainSerializer(serializers.ModelSerializer): pfam_id = PfamSerializer class Meta: model = Domains fields = ['pfam_id','description','start','stop'] api.py imports .. class ProteinDetail(mixins.RetrieveModelMixin, generics.ListAPIView): serializer_class = DomainSerializer queryset = Domains.objects.all() def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) urls.py imports .. urlpatterns = [ path('api/protein/<int:pk>', api.ProteinDetail.as_view(), name='protein_api'), ] This is the result I'm getting, but instead of showing pfam_id as a foreign key I want it to show the contents of pfam. Im not sure why my PfamSerializer isn't working in this scenario. [1]: https://i.stack.imgur.com/LfAOC.png -
Django Authorization Token returns AnonymousUser
I'm trying to get the user from a request. My reactjs/postman client sends the token in the header as follow: 'Authorization' : 'Token token_string' For some reason, when I using self.request.user in the view (GET request) I'm getting AnonymousUser. The token is valid, using the following code I'm getting the correct user, not AnonymousUser: from rest_framework.authtoken.models import Token from django.shortcuts import get_object_or_404 user = get_object_or_404(Token, pk=token_string).user Here is my setting.py MIDDLEWARE: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Here is my User model: class User(django.contrib.auth.models.User): avatar = models.URLField(max_length=255, blank=True) date = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=256) Note: when I'm calling the request using the browser after logging in to Django admin I'm getting the user properly. -
How to i merge this two JS work together and calculate time
I am making Time tracking app. Here i have already did time starting and stop event and stored that total timing data. But i need to implement further that idle time tracking without any movement of mouse, keyboard or any thing else. That time store data and final result should be like this :::::: Total time today : 6 hr 30 min idel time today : 1hr 30 min Or Working time today: 5hr 00 min. But i don't know how to get this. This is my Vue.js Script :: <script> var NavbarApp = { data() { return { seconds: {{ active_entry_seconds }}, trackingTime: false, showTrackingModal: false, timer: null, entryID: 0, startTime: '{{ start_time }}' } }, delimiters: ['[[',']]'], methods: { startTimer() { fetch('/dashboard/projects/api/start_timer/',{ method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' } }) .then((response) =>{ return response.json() }) .then((result) =>{ this.startTime = new Date() this.trackingTime = true this.timer = setInterval(() => { this.seconds = (new Date()- this.startTime) / 1000 }, 1000) }) }, stopTimer(){ fetch('/dashboard/projects/api/stop_timer/',{ method: 'POST', headers: { 'Content-Type':'application/json', 'X-CSRFToken': '{{ csrf_token }}' } }) .then((response) =>{ return response.json() }) .then((result) =>{ this.entryID = result.entryID this.showTrackingModal = true this.trackingTime = false window.clearTimeout(this.timer) }) }, discardTimer(){ fetch('/dashboard/projects/api/discard_timer/',{ … -
Multi-table inheritance and two many to many via through model not working in admin inline
I'm trying to create navigation menu from the django admin as per user's requirement. The Model look like this: class MenuItem(models.Model): title = models.CharField(max_length=200, help_text='Title of the item') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_published = models.BooleanField(default=False) def __str__(self): return self.title class Page(MenuItem): """ To display non-hierarchical pages such as about us, or some page in menu """ slug = models.SlugField(max_length=200, unique=True, help_text='End of url') content = HTMLField(help_text='Contents of the page') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) class Category(MenuItem): """ For hierarchical display eg. in navigation menu use Category and Articles. """ slug = models.SlugField(max_length=200, unique=True, help_text='End of url') class Meta: verbose_name_plural = 'categories' Page and Category can be different types of menu items, so, I used inheritance. Now I want to bind the MenuItem to a Menu, hence I added two more models below. class Menu(models.Model): title = models.CharField(max_length=200, unique=True, help_text='Name of the menu.') is_published = models.BooleanField(default=False) item = models.ManyToManyField(MenuItem, through='MenuLevel', through_fields=['menu', 'menu_item']) def __str__(self): return self.title class MenuLevel(models.Model): menu = models.ForeignKey(Menu, on_delete=models.CASCADE) menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE, related_name='items') level = models.IntegerField(default=0) parent = models.ForeignKey(MenuItem, on_delete=models.CASCADE, related_name='parent', null=True, blank=True) I need the parent key to menu item to traverse through the menu items from parent to children and level to sort the … -
Django admin search box: searching by field names
I'm trying to customize django admin search box for models so I can search for multiple fields at once Here is what I have: class Person(models.Model): name = models.CharField(max_length=200) phone = models.CharField(max_length=200) class SearchMixin(admin.ModelAdmin): def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super(TargetedSearchFieldMixin, self).get_search_results( request, queryset, search_term) search_words = search_term.split() if search_words: q_objects = [Q(**{field + '__icontains': word}) for field in self.search_fields for word in search_words] queryset |= self.model.objects.filter(reduce(or_, q_objects)) return queryset, use_distinct This will work for person model if we give input like this: jack +1558844663 Will search for people with phone number +1558844663 and name jack I want to change the method to accept inputs with field names like this: name=jack&phone=+1558844663 -
DJANGO form from models - select options from ajax jquery
I can't find in DJANGO docs solutions. I have a form with two select fields (Foreign key). Django automatically create options from models, but i want second field is filled with ajax, depending on what we choose in the first field. For now I do in document ready $('#id').find('option').remove().end() but it's not elegant at all ;) How to set DJANGO form not to fetch data for a specific field automatically? -
how to increase amount if date and time greater than 24 hours in Django?
**My booking views.py file. ** def booking(request): context = { 'amount': 100 } ** my booking.html** <p>Amount = RS {{amount}} </p> **I want to increase this amount.** I want to increase the above mention amount when user select data and time greater than 24 hours. if your do so then the amount increase automatically. -
Calling WebSocket Class Function from view is not working in Django Rest Framework
I wanted to call a function from the consumer file function receive. I'm using that method. but this is not working. this is a consumer.py class ChatConsumer(AsyncWebsocketConsumer): def getUser(self, userId): ... Some Code def saveMessage(self, message_obj): ... Some Code async def connect(self): ... Some Code async def receive(self, text_data, type='receive'): ... Some Code async def chat_message(self, event, type='chat_message'): ... Some Code async def disconnect(self, close_code): ... Some Code this is a serializers.py class CreateChatMessageView(APIView): cls_consumers = consumers.ChatConsumer() channel_layer = get_channel_layer() message_obj.save() chat_message_serializer = CreateChatMessageResponseSerializer(message_obj) async_to_sync(channel_layer.group_send)( str(message_obj.chat_room.id), { 'type': 'receive', 'message': chat_message_serializer.data } ) print("Ok") ... Some Code -
How to consume messages from Kafka consumer to Django app in new docker container?
The Django server is going stuck if Kafka-comsumer starts. What should I do? I want to run this consumer as a sidecar container. Can anyone help me? consumer = KafkaConsumer("my-topic", bootstrap_servers=\['{}:{}'.format(HOST, PORT)\],auto_offset_reset="earliest", value_deserializer=lambda x: ReadHelper().json_deserializer(x), group_id="my_consumer_group" ) for msg in consumer: print(msg) -
How To Automatically Create Objects Of Django Model While Creation Another Model Objects
I Want To Create Object For "ProductOut" Model When "CusOrder" Model Is Being Created Here Is My Code class CusOrder(models.Model): cus_name = models.CharField(max_length=100) cus_number = models.CharField(max_length=11) product = models.ManyToManyField(Product) qty = models.IntegerField(default=0) sell_price = models.IntegerField(default=0) def __str__(self): return self.cus_name def save(self,*args,**kwrgs): ProductOut.objects.create( refrence=self.cus_number, stock_out = self.qty, sell_price = self.sell_price, product = self.product.P_name ) super(CusOrder,self).save(*args,**kwrgs) class ProductOut(models.Model): refrence = models.ManyToManyField(CusOrder) stock_out = models.IntegerField(default=0) sell_price = models.IntegerField(default=0) product = models.ForeignKey(Product,on_delete=models.CASCADE) def __str__(self): return self.refrence.cus_number But I am Getting a ValueError which Is '"<CusOrder: Asif>" needs to have a value for field "id" before this many-to-many relationship can be used.' When I want to save a CusOrder Object here Is My Whole class Catagory(models.Model): name = models.CharField(max_length=60) def __str__(self): return self.name class Product(models.Model): P_name = models.CharField(max_length=30) stock_in = models.IntegerField(default=0) unit_price = models.IntegerField(default=0) cata = models.ForeignKey(Catagory, on_delete=models.CASCADE) def __str__(self): return self.P_name class CusOrder(models.Model): cus_name = models.CharField(max_length=100) cus_number = models.CharField(max_length=11) product = models.ManyToManyField(Product) qty = models.IntegerField(default=0) sell_price = models.IntegerField(default=0) def __str__(self): return self.cus_name def save(self,*args,**kwrgs): ProductOut.objects.create( refrence=self.cus_number, stock_out = self.qty, sell_price = self.sell_price, product = self.product.P_name ) super(CusOrder,self).save(*args,**kwrgs) class ProductOut(models.Model): refrence = models.ManyToManyField(CusOrder) stock_out = models.IntegerField(default=0) sell_price = models.IntegerField(default=0) product = models.ForeignKey(Product,on_delete=models.CASCADE) def __str__(self): return self.refrence.cus_number class ReturnedProduct(models.Model): cus_number = models.ForeignKey(CusOrder,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) qty … -
How to create custom Response in drf generic ListAPIView
I'm showing reviews of each products, so If a product don't have a review yet then i want to show a response like there 'No reviews yet" class ShowReviews(generics.ListAPIView): serializer_class = ReviewSerializer filter_backends = [filters.DjangoFilterBackend, OrderingFilter] filterset_class = ReviewFilter ordering_fields = ['rating', 'id'] lookup_field='product_slug' def get_queryset(self): slug = self.kwargs['product_slug'] return ReviewRatings.objects.filter(product__slug=slug, is_active=True) And please share the link if anything mentioned about this in docs because I'm unable to find any solutions. -
killing docker container from docker desktop
Created an django app and dockerize it and then before I stopped the container I removed the app and then I could not remove the container yet Can you help me please to remove docker container once I clicked remove button it says that removing container from docker -
Long Processing within Django ModelAdmin Form
I have a custom form in a admin.ModelAdmin where I use to upload some CSV data with a file upload. Sometimes, processing this CSV file takes longer than the HTTP Worker timeouts will allow, forcing me to split up the CSV file into smaller chunks that will not trip the worker timeouts. I need to find a way to avoid splitting up the CSV into separate chunks to upload one at a time. I was researching how I might resolve this issue, and I am having a hard time finding any resources I might be able to learn from, like a tutorial. What are some common patterns and best practices when I need to do something long-running (>30s) in Django Admin? I am looking for pointers, guides, and tutorials. Thank you! -
How to include the start date and end date while filtering in django
views.py if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) check_box_status = request.POST.get("new_records", None) print(check_box_status) drop_down_status = request.POST.get("field") print(drop_down_status) if check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__range=(f_date, t_date)) The following code get_records_by_date = Scrapper.objects.filter(start_time__range=(f_date, t_date)) is unable to include the t_date. Is there any solution to include the t_date. -
Object created in view isn't rendering in template
I'm creating a new object in a view through an external function. This is the code: def index(request): sousei = suii_scratch(SOUSEI_URL) s_jikan = sousei[0] s_suii = sousei[1] sousei_obj = Sousei.objects.create(jikan=s_jikan, suii=s_suii) #print(sousei_obj) context = { sousei_obj : 'sousei', } return render(request, 'index.html', context) The external function is returning two values, that are being catched in s_jikan and s_suii variables. These variables are then used to create a new object (the model has only this two fields). If I uncomment the print statement, I get printed the __str__ method of the model with the newly obtained data from the external function. Also, if I check the admin, the new record in the database is beign saved correctly. Until here seems everything is working fine, but when passing the created object to the template I can't get it rendered. This is template code: {% if sousei %} <p>{{sousei.jikan}}</p> <p>{{sousei.suii}}</p> {% else %} <p>No data.</p> {% endif %} But I keep getting there is no data. What am I missing? -
How to create a class that can handle request data
I will have a input data that look like this (will be POST by postman) { "COMMAND_ID":"56789", "CARRIER_ID":"HF2202109W061", "CURR_GRP":"", "CURR_DEV":"", "CURR_LOC":"FAKE1-1", "DEST_GRP":"", "DEST_DEV":"", "DEST_LOC":"FAKE2-1", "MOVE_PRIORITY":"50" } and my views.py look like this class PalletMoveAPI(APIView): authentication_classes = [SessionAuthentication , BasicAuthentication] permission_classes = [IsAuthenticated,] def post(self,request,format=None,*args,**kwargs): try: inputdata = request.data testdata= { "DATAID":"", "CommandID":inputdata["COMMAND_ID"], "Priority":inputdata["MOVE_PRIORITY"], "Replace":0, "VehicleID":"", "CarrierID1":inputdata["CARRIER_ID"], "WCount1":inputdata["WAFER_QTY"], "SourcePort1":inputdata["CURR_LOC"], "DestPort1":inputdata["DEST_LOC"], "CarrierID2":"", "WCount2":"", "SourcePort2":"", "DestPort2":"" } pallet_move = requests.post('http://10.13.10.43:10000/api/command/send',json= testdata) if pallet_move.status_code in [HTTPStatus.OK,HTTPStatus.CREATED]: event = Post_successed() return JsonResponse({"code":event.code,"detail":event.description},status=event.status,safe=False) except Exception as e: event = Error(str(e)) return JsonResponse({"code":event.code,"detail":event.description},status=event.status,safe=False) how can i create a class or function to handle to include the request part. like i wan to make that part reusable. a class that can take in request data and then return as the 'testdata' format shown above -
DRF CreateModelMixin with additional fields
I'm using GenericAPIView with the CreateModelMixin to create a model instance. I need my serializer to add additional fields that aren't defined by the user. My Serializer.create method is already set up for this, but I don't know how to pass fields through to the CreateModelMixin.create method. Here's a minimal version of what I have: class Foo(mixins.CreateModelMixin, generics.GenericAPIView): permission_classes = [IsAuthenticated] def get_serializer_class(self): return FooSerializer def post(self, request): return self.create( request, requester=request.user # Additional field ) This doesn't work - the requester field isn't passed to FooSerializer.save, so FooSerializer throws an error when it attempts to access requester in FooSerializer.create. Before, I was using APIView and calling the serializer directly, so I could simply: serializer = FooSerializer(data=request.data) if serializer.is_valid(): foo = serializer.save(requester=request.user) Is there any way to achieve this with the GenericAPIView? I want to embrace DRF's DRY-ness and avoid calling serializers in every endpoint method. -
Why do I keep getting 403 error in Django after using csrftoken in Ajax POST call?
I am doing an Ajax POST request to get news articles. I have put a csrftoken in the headers, but I still keep getting a 403 error. I have looked online and have tried many solutions, but I keep getting a 403 error. Why is this? $('#search-articles').on('submit', function(event) { event.preventDefault(); document.getElementById("loading").style.display = "block"; document.getElementById("search-bar").style.display = "none"; document.getElementById("articles").style.display = "none"; function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } $.ajax({ url: "{% url 'stocks_sites:get_news_articles' %}", type: "POST", data: { "q": document.getElementById("search-articles").value, csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val() }, headers: { "X-CSRFToken": getCookie("csrftoken"), // don't forget to include the 'getCookie' function }, success: function(response) { document.getElementById("loading").style.display = "none"; document.getElementById("search-bar").style.display = "block"; document.getElementById("articles").style.display = "block"; $("#search-bar").html(response[0]); $("#articles").html(response[1]); } }) }) -
Django, pandas, excel: uploading files, parsing them with pandas in Django
I have a big command-line script for parsing data in Excel (with pandas) and I want to wrap it with Django. I've tried both uploading files thru request.FILES and pandas, but get stuck on uploading file and, for example, saving it (not necessarily but just to check the upload for now). Haven't had any problems with other apps on Django which didn't require uploading and parsing anything external and thought that would be much easier..:) I've also tried Redirecting, doesn't really work, the only redirect which is actually happening is action in the form tag.. Here are the code snippets: views.py: def uploads(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): excel_file = request.FILES['document'] excel_file.save() return render(request, 'index.html') else: form = DocumentForm() return render(request, 'index.html', {'form': form}) models.py class Document(models.Model): document = models.FileField(upload_to="files/") forms.py: class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('document', ) index.html: <form action="{% url 'reports'%}" method="post" enctype="multipart/form-data" > {% csrf_token %} <span> Upload .xlsx file <input type="file" name="document" /> </span> <button type="submit"> SUBMIT </button> </form>