Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I define the ManyToManyField name?
I have this relationship Class Item(models.Model): pass Class Category(models.Model): items = models.ManyToManyField(Item) I can define the field name as items for category and access it via category.items but I want to define a field name for Item too as item.categories rather than the default item.category How can I achieve it? -
detail : "CSRF Failed: CSRF token missing." getting this on network when trying to create or delete or put data in angular 13 and DRF
i need to create source, delete it and update as well, butting getting the same error again and again. //component.html <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <div class="container mt-5"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search..." [(ngModel)]="filterTerm" /> </div> <ol> <li *ngFor="let source of sources$ | async | filter: filterTerm"> <div class="card"> <div class="card-body"> <h5 class="card-title">{{source.name}}</h5> <p>URL:- <a href ='{{source.url}}'>{{source.url}}</a></p> <a class="btn btn-primary" href='fetch/{{source.id}}' role="button" style="margin-left:5px ">Fetch</a> <button class="btn btn-primary" (click)="deleteSource(source.id)" style="margin-left:5px">Delete </button> <button class="btn btn-primary" (click)="editSource(source.id, source)" style="margin-left:5px ">Edit </button> <br> </div> </div> </li> </ol> </div> //service.ts export class SourcesService { API_URL = 'http://127.0.0.1:8000/sourceapi/'; constructor(private http: HttpClient) { } /** GET sources from the server */ Sources() : Observable<sources[]> { return this.http.get<sources[]>(this.API_URL,); } /** POST: add a new source to the server */ addSource(source : sources[]): Observable<sources[]>{ return this.http.post<sources[]> (this.API_URL, source); //console.log(user); } deleteSource(id: string): Observable<number>{ return this.http.delete<number>(this.API_URL +id); } // component.ts export class SourcesComponent implements OnInit { filterTerm!: string; sources$ !: Observable<sources[]>; // deletedSource !: sources; constructor(private sourcesService: SourcesService) { } // prepareDeleteSource(deleteSource: sources){ // this.deletedSource = deleteSource; // } ngOnInit(): void { this.Source(); } Source(){ this.sources$ = this.sourcesService.Sources() } deleteSource(id : string){ console.log(id) this.sourcesService.deleteSource(id).subscribe(); } I tried, providing the header and also tried the steps got in the question … -
Django - MySQL (1170, "BLOB/TEXT column 'object_path' used in key specification without a key length
I've updated the Django model field from CharField to TextField. I got the below error while applying migrations in MySQL. django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'my_column' used in key specification without a key length") Django version: 2.2.2 Note: This column in included in unique_together in Meta. -
How to optimize N+1 SQL queries when serializing a post with mptt comments?
Good afternoon. I have the following serializer for a detailed post: class ArticleDetailSerializer(serializers.ModelSerializer): author = ArticleAuthorSerializer(read_only=True) comments = CommentSerializer(many=True, read_only=True) class Meta: model = Article fields = '__all__' Comment Serializer: class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' def get_fields(self): fields = super(CommentSerializer, self).get_fields() fields['children'] = CommentSerializer(many=True, required=False, source='get_children') return fields When working with a list of comments, I get 2 sql queries if I work with get_cached_trees() class CommentListAPIView(generics.ListAPIView): serializer_class = serializers.CommentSerializer queryset = Comment.objects.all().get_cached_trees() But how do you get the same thing to work for an article with a list of comments? class ArticleDetailAPIView(generics.RetrieveAPIView): serializer_class = serializers.ArticleDetailSerializer queryset = Article.custom.all() lookup_field = 'slug' def get_queryset(self): queryset = self.queryset.prefetch_related(Prefetch('comments', queryset=Comment.objects.all().get_cached_trees())) return queryset I used prefetch_related() but it didn't work. I used Prefetch(), it gave me an error: 'list' object has no attribute '_add_hints' I seem to be lost in the ability to optimize the mptt comments for the article. But if you use the same comments, rendering according to the documentation in the Django template, then this problem is not observed. I ask for your help, dear programmers and experts. -
Django login/ Payload
This is weird. I have created login functions so many times but never noticed this thing. when we provide a username and password in form and submit it. and It goes to server-side as a Payload like this csrfmiddlewaretoken: mHjXdIDo50tfygxZualuxaCBBdKboeK2R89scsxyfUxm22iFsMHY2xKtxC9uQNni username: testuser password: 'dummy pass' #same as i typed(no encryption) I got this in the case of Incorrect creds because the login failed and it won't redirect to the other page. but then I tried with Valid creds and I set the Preserve log turned on in the Chrome network tab. then I checked there and still, I can see the exact entered Username and password. for the first time, I thought i might have missed some encryption logic or something else i dont know. but then i tried with multiple Reputed tech companies and i can still see creds in the payload. Isn't it wrong? It's supposed to be in the encrypted format right? -
Django 'model' object is not iterable when response
i hvae 2 model. And the two models are connected to the ManyToManyField. models.py class PostModel(models.Model): id = models.AutoField(primary_key=True, null=False) title = models.TextField() comments = models.ManyToManyField('CommentModel') class CommentModel(models.Model): id = models.AutoField(primary_key=True, null=False) post_id = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField() and serializers.py class CommentModel_serializer(serializers.ModelSerializer): class Meta: model = MainCommentModel fields = '__all__' class PostModel_serializer(serializers.ModelSerializer): comment = MainCommentModel_serializer(many=True, allow_null=True, read_only=True) class Meta: model = MainModel fields = '__all__' and views.py @api_view(['GET']) def getPost(request, pk): post = PostModel.objects.filter(id=pk).first() comment_list = CommentModel.objects.filter(post_id=post.id) for i in comments_list: post.comments.add(i) serializer = PostModel_serializer(post, many=True) return Response(serializer.data) There is an error when I make a request. 'PostModel' object is not iterable and The trackback points here. return Response(serializer.data) I tried to modify a lot of code but I can't find solutions. Please tell me where and how it went wrong -
Django session variable returns None?
I want to get value of j in test function, but it returns None, How i get value of this session variable. This is index function where session variable is created and passing it. def index(request): j = '' if request.method == "POST": form = InputForm(request.POST) if form.is_valid(): form.save() try: ids = form.cleaned_data['git_Id'] print(ids) obj = sql() query = f""" SELECT request_id FROM request_form_db.request_form_mymodel where git_Id= '{ids}' ; """ print(query) p = obj.fetch_query(query) print("Query Result", p) for i in p: print("Result[0] : ", i[0]) print("Result : ", p) i = i[0] j = i approve_url = f"http://127.0.0.1:8000/form/test?request_id={i}" print("Url : ", approve_url) form = InputForm() else: form = InputForm() print('J : ', j) request.session['j'] = j print('Request ID Sent : ', j) return render(request, 'home.html', {'form': form}) This is test function where i want to getting value of j, but here it returns None. def test(request): pro = request.session.get('j') print("Request ID from Index View : ", pro) if request.method == "POST": form = TestForm(request.POST) if form.is_valid(): print("Form is Valid") selected = form.cleaned_data.get('myfield') print(selected) else: rq = request_id["request_id"] s = sql() query = f"""update request_form_db.request_form_mymodel set is_approved=1 where request_id = '{rq}' """ print(query) s.update_query(query) print("Updated Successfully") form = TestForm() else: form = … -
Why django form post with errors updates instance
I have a standard user update form like @login_required() def personal(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) if user_form.is_valid(): user = user_form.save() update_session_auth_hash(request, user) messages.success(request, 'Your personal data has been changed successfully!') return redirect('profile') else: user_form = UserForm(instance=request.user) context = { 'form': user_form, } return render(request, 'personal.html', context) The problem here is in the line user_form.is_valid(). It runs validation logic which collects an error when username is already taken by another user. In this case we have ValidationError raised but the instance in this form is updated nevertheless due to code in django's construct_instance function logic: def construct_instance(form, instance, fields=None, exclude=None): """ Construct and return a model instance from the bound ``form``'s ``cleaned_data``, but do not save the returned instance to the database. """ ... f.save_form_data(instance, cleaned_data[f.name]) ... I found this behavior very strange. How can I avoid updating user's instance fields with wrong values if I need, say, display initial user's username on the top of my page? -
Django QuerySet .order_by() method
I have this code down here and from my understanding order_by over writes the default behavior of the ordering option in the model’s Meta. see the documentation here https://docs.djangoproject.com/en/4.1/ref/models/querysets/#order-by my question is what criteria does the order_by() in this case use to order the QuerySet if there are no fields provided? Does it make a difference having it there? order.discounts.filter(voucher_id=OuterRef("pk")) .order_by() .values("voucher_id") .annotate(Sum("amount")) .values("amount__sum") ) -
Failed to load resource: net::ERR_CONNECTION_REFUSED 127.0.0.1:8000/store/products/1/images/:1 Failed to load resource:
I am trying to connect two server 127.0.0.1:60000 and localhost:8001 for connect two server and run localhost:8001 file its connect with 127.0.0.1:60000 port, but its give me #Failed to load resource: net::ERR_CONNECTION_REFUSED here is my code **settings.py** this is seetings.py enter image description here enter image description here i expect enter image description here this is output -
How to learn Django and do project in Django
Previous two months I am learning Django and I do some projects like CRUD, TODO-LIST, and some more basic project. But after this, I want to make a contract management project so I perform tasks like adding a user session and doing some code in view.py. I get so difficult so please suggest me lecture or tutorial there I can learn (how to code in view.py ). thanks, guys for helping me. -
os.getcwd() raise Exception with django dev server
I have a django project running inside docker, and the service is up with the command of python manage.py runserver, with file autoreload open, and using threadings. My code invokes shutil.make_archive() which will then invoke os.getcwd(), and from time to time, os.getcwd() will raise FileNotFoundError, by searching more information, now I realized that the error might be caused by the path is no more there because the path is deleted by somewhere else after I enter the path. The error only raised sometimes and I couldn't find a stable way to reproduce it, once it happens, I can fix the problem by making any code changes to trigger file autoreload or restart the docker service, looks like make sure the process restarts will do the help, otherwise the error keeps raising. When things going properly, os.getcwd() will return my django project root dir path. And I'm 100% sure my code does nothing related with dir manipulation like os.chdir(). So in a nutshell, the django server works fine, suddenly os.getcwd() starts to raise error until I restart the process. My question is, what could be the root cause? is it possible that python manage.py runserver might cause any issue? Python: v3.8.6 … -
Using and supplying binaries for Yuglify or other filters with Django Compressor?
We've got Django-Compressor working nicely with compressor.filters.jsmin.rJSMinFilter which is installed by default and given by the default setting COMPRESS_FILTERS = {'css': ['compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.rCSSMinFilter'], 'js': ['compressor.filters.jsmin.rJSMinFilter']}, and we want to add compressor.filters.yuglify.YUglifyJSFilter to this, but unlike rJSMinFilter it isn't installed by default, and we don't know how to supply COMPRESS_YUGLIFY_BINARY. If we go to Yuglify's GH page we see the repo but don't know what file(s) to use or where to place them within our Django project. The examples show how npm install yuglify, but we don't know what npm is or how to use it. Probably a really stupid question but how can we supply it? We need this done in a way that we don't have to individually install things on different machines. Is it possible to include the Yuglify file(s) somewhere in our Django project, so things work as nicely as they did with rJSMinFilter, which was installed by default? -
I need to Delete any object from my DRF / django connected database through angular 13
I am getting the id which i have to delete but the last line of service.ts that is of delete method is not getting executed... the files and code snippets I used are : - COMPONENT.HTML <li *ngFor="let source of sources$ | async | filter: filterTerm"> <div class="card"> <div class="card-body"> <h5 class="card-title">{{source.name}}</h5> <p>URL:- <a href ='{{source.url}}'>{{source.url}}</a></p> <a class="btn btn-primary" href='fetch/{{source.id}}' role="button">fetch</a> <button class="btn btn-primary" (click)="deleteSource(source.id)">delete </button> <br> </div> </div> </li> I tried to console the id geeting from html and the Id i am getting is correct. //component.ts export class SourcesComponent implements OnInit { filterTerm!: string; sources$ !: Observable<sources[]>; // deletedSource !: sources; constructor(private sourcesService: SourcesService) { } // prepareDeleteSource(deleteSource: sources){ // this.deletedSource = deleteSource; // } ngOnInit(): void { this.Source(); } Source(){ this.sources$ = this.sourcesService.Sources() } deleteSource(id : string){ console.log(id) this.sourcesService.deleteSource(id); } //service.ts export class SourcesService { API_URL = 'http://127.0.0.1:8000/sourceapi'; constructor(private http: HttpClient) { } // let csrf = this._cookieService.get("csrftoken"); // if (typeof(csrf) === 'undefined') { // csrf = ''; // } /** GET sources from the server */ Sources() : Observable<sources[]> { return this.http.get<sources[]>(this.API_URL,); } /** POST: add a new source to the server */ addSource(source : sources[]): Observable<sources[]>{ return this.http.post<sources[]> (this.API_URL, source); //console.log(user); } deleteSource(id: string): Observable<number>{ … -
Faceting with Django Rest Framwork / Django Filter
Dear fellow overflowers, I’m currently building an API based on Django Rest Framework with Django Filter. Search, filtering and sorting works reasonably well, though I was wondering about filter facets. Imagine there’s a “Person” model and you’d like to allow users to filter by the first letter peoples’ names. You don’t want users to run into a “no results” situation, so you only want to suggest the letters that match at least one person. What is a good way to provide a list of choices (the facets) for each filter? Does it make sense to use a different endpoint that provides choices only? To me, it would feel right to declare facets inside the FilterSet subclass, because it’s the place where anything filter-related happens. Looking forward to your comments! Julian PS: Typically, I use ElasticSearch in situations like this, but I wonder if there’s an idiomatic solution in plain DRF/DF. # models.py from django.db import models class Person(models.Model): name = models.CharField(max_length=200) # filters from django_filters import rest_framework as filters from django.db.models.functions import Substr def get_first_letter_choices(): # Create choices letters = Person.objects \ .all() \ .annotate(first_letter=Substr('name', 1, 1)) \ .values_list("first_letter", flat=True) \ .distinct() return [(letter, letter, ) for letter in letters] … -
Cannot assign "'10000'": "Jobs.client_id" must be a "Clients" instance
I have two tables, Jobs and Clients. class Jobs(models.Model): client_id = models.ForeignKey(Clients,db_column='client_id',on_delete=models.CASCADE) class Clients(models.Model): created = models.DateTimeField() modified = models.DateTimeField(auto_now=True) I have Jobs data in json format. jobs_data = { 'client_id':'10000', .... } When I want to save this data into Jobs table I get the ValueError: Cannot assign "'10000'": "Jobs.client_id" must be a "Clients" instance. To save the table I have tried jobs_obj = Jobs.objects.create(**v['Job']) How can I fix this problem ? -
django.core.exceptions.ImproperlyConfigured: Set the CRYPTO_KEY environment variable How do I fix it ?I can't start the project
After I run python manage.py runserver gives this error. The Output in: Traceback (most recent call last): File "C:\new-folder\venv\Lib\site-packages\environ\environ.py", line 273, in get_value value = self.ENVIRON[var] ~~~~~~~~~~~~^^^^^ File "<frozen os>", line 678, in __getitem__ KeyError: 'CRYPTO_KEY' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\new-folder\manage.py", line 21, in <module> main() File "C:\new-folder\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\new-folder\venv\Lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\new-folder\venv\Lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\new-folder\venv\Lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\new-folder\venv\Lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\new-folder\venv\Lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\new-folder\venv\Lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: ^^^^^^^^^^^^^^ File "C:\new-folder\venv\Lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\new-folder\venv\Lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\new-folder\venv\Lib\site-packages\django\conf\__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File … -
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.