Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display login user full details on profile page in django?
I'm new to django i have created login and logout and signup form.when i will try to display login user details book.objects.all() all login user details displaying . please tell me how to display particular login user all signup details like photo address and all my model user fields with code please.. I already tried with get(username=username) but it not working.. views.py --------- from django.shortcuts import render,redirect from django.contrib.auth.decorators import login_required from django.http import HttpResponse,HttpResponseRedirect from django.contrib.auth import authenticate, login, logout from testapp.forms import signupform, UserForm,UserProfileForm from django.contrib.auth.hashers import check_password from testapp.models import Maas def homeview(request): return render(request,'testApp/home.html') @login_required def feedbackview(request): return render(request,'testApp/feedback.html') def logoutview(request): return render(request,'testApp/logout.html') def logoutview(request): return render(request,'testApp/logout.html') def akhilview(request): return render(request,'testApp/akhil.html') def siriview(request): return render(request,'testApp/siri.html') def depview(request): return render(request,'testApp/dep.html') def maas(request,username): obj=Maas.objects.get(username=username) return render(request,'testApp/profile.html',{'obj':obj}) def subview(request): return render(request,'testApp/sub.html') def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) form = signupform(request.POST,request.FILES) profile_form=UserProfileForm(data=request.POST) if user_form.is_valid() and form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() form.save() profile = profile_form.save(commit=False) profile.user = user if 'photo' in request.FILES: profile.picture = request.FILES['photo'] profile.save() return redirect("/accounts/login") registered = True else: print(user_form.errors,form.error,profile_form.errors) else: form=signupform() profile_form = UserProfileForm() user_form = UserForm() return render(request,'testApp/singup.html',{'user_form': user_form,'profile_form':profile_form,'registered': registered,'form':form}) def user_login(request): if request.method == 'POST': # … -
How to solve this error..."The included URLconf...does not appear to have any patterns in it."
I am a beginner who started learning Django. The error message is... django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. /books/urls.py from django.urls import path from . import views app_name = 'books' urlpatters = [ path('', views.BooksModelView.as_view(), name='index'), path('book/', views.BookList.as_view(), name='book_list'), path('author/', views.AuthorList.as_view(), name='author_list'), path('publisher/', views.PublisherList.as_view(), name='publisher_list'), path('book/<int:pk>/', views.BookDetail.as_view(), name='book_detail'), path('author/<int:pk>/', views.AuthorDetail.as_view(), name='author_detail'), path('publisher/<int:pk>/', views.PublisherDetail.as_view(), name='publisher_detail'), ] /books/views.py from django.views.generic.base import TemplateView from django.views.generic import ListView from django.views.generic import DetailView from books.models import Book, Author, Publisher # TemplateView class BooksModelView(TemplateView): template_name = 'books/index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['model_list'] = ['Book', 'Author', 'Publisher'] return context # ListView class BookList(ListView): model = Book class AuthorList(ListView): model = Author class PublisherList(ListView): model = Publisher # DetailView class BookDetail(DetailView): model = Book class AuthorDetail(DetailView): model = Author class PublisherDetail(DetailView): model = Publisher /books/models.py from django.db import models class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField('Author') publisher = models.ForeignKey('Publisher', on_delete=models.CASCADE) publication_date = models.DateField() def __str__(self): return self.title class Author(models.Model): name = models.CharField(max_length=50) salutation = models.CharField(max_length=100) email = models.EmailField() def __str__(self): return self.name class Publisher(models.Model): name = models.CharField(max_length=50) address = … -
React-Redux-Django for a search filter
How to implement a Search Filter list using react-redux on front-end and django as a backend ? Here is my main file <div> <SearchBar/> <ListView/> </div> The SearchBar is handleFormSubmit = e => { e.preventDefault(); const name = e.target.elements.name.value; const age = e.target.elements.age.value; const height = e.target.elements.height.value; this.props.search(name, age, height); }; render() { return ( <div> ... </div> } const mapDispatchToProps = dispatch => { return { search: (name, age, height) => dispatch(actions.Search_Results(name, age, height)) } }; export default connect(null, mapDispatchToProps)(withRouter(SearchBar)); The ListView is render() { return ( <div> <CustomPaginationActionsTable rows={this.props.data}/> </div> ); } } const mapStateToProps = (state) => { return { data: state.results, } }; export default connect(mapStateToProps, null)(withRouter(ListView)); The Action is export const Search_Results = (name, age, height) => { return dispatch => { axios.get("http://127.0.0.1:8000/api/") .then(res => { const mLab = res.data dispatch(presentResult(mLab)) }); } }; export const presentResult = results => { return { type: actionTypes.PRESENT_RESULTS, results: results } }; The Reducer is const presentResult = (state, action) => { return updateObject(state, { results: action.results }); }; const reducer = (state = initialState, action) => { switch (action.type) { case actionTypes.SEARCH_RESULTS: return searchResult(state, action); default: return state; } }; export default reducer; The updateObject simply code: … -
Opening a file in google docs using pydrive
I have the option of generating an html file from django querysets. Everything works well and when clicking on the corresponding button, it will be redirected to the resulting page. Now I need to make it so that the generated file opens not in the application but in google docs. To do this, I use the pydrive library. According to the documentation, I created the file pydrive.py and client_secrets.json for the test. pydrive_gd.py from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() gauth.LocalWebserverAuth() file1 = drive.CreateFile({'title': 'Hello.txt'}) # Create GoogleDriveFile instance with title 'Hello.txt'. file1.SetContentString('Hello World!') # Set content of the file from given string. file1.Upload() The test works well and after logging into my Google account I get a message Authentication successful. Next step I try to connect pydrive code to my django view. Note that the views.py, client_secrets.json, pydrive_gd.py files are in the same directory. I start adding code to the views.py file and as soon as I add the line gauth.LocalWebserverAuth() views.py #Other import from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() gauth.LocalWebserverAuth()#--->ERROR I get an error raise InvalidConfigError('Invalid client secrets file %s' % error) pydrive.settings.InvalidConfigError: Invalid client secrets file ('Error opening … -
How can we store AR WorldMap to server side?
I want to store WorldMap session remotely. https://developer.apple.com/documentation/arkit/arworldmap To get AR Session:- sceneView.session.getCurrentWorldMap { worldMap, error in guard let map = worldMap else { self.showAlert(title: "Can't get current world map", message: error!.localizedDescription); return } // Add a snapshot image indicating where the map was captured. guard let snapshotAnchor = SnapshotAnchor(capturing: self.sceneView) else { fatalError("Can't take snapshot") } map.anchors.append(snapshotAnchor) do { let data = try NSKeyedArchiver.archivedData(withRootObject: map, requiringSecureCoding: true) try data.write(to: self.mapSaveURL, options: [.atomic]) DispatchQueue.main.async { self.loadExperienceButton.isHidden = false self.loadExperienceButton.isEnabled = true } } catch { fatalError("Can't save map: \(error.localizedDescription)") } } -
Collect html form data and send as a json payload to an api
<script> $(document).ready(function(){ $("#submitform").click(function(e) { var MyForm = JSON.stringify($("#myform").serializeJSON()); console.log(MyForm); $.ajax( { url : "https://test.theteller.net/checkout/initiate", type: "POST", data : MyForm, }); }); }); </script> <form method="post" action="/"> <div class="form-row"> <div class="form-group col-md-6"> <label for="merchant_id">merchant_id</label> <input type="text" class="form-control" id="merchant_id" placeholder="merchant_id"> </div> <div class="form-group col-md-6"> <label for="transaction_id">transaction_id</label> <input type="text" class="form-control" id="transaction_id" > </div> <div class="form-group col-md-6"> <label for="desc">desc</label> <input type="text" class="form-control" id="desc" > </div> <div class="form-group col-md-6"> <label for="amount">amount</label> <input type="number" class="form-control" id="amount"> </div> <div class="form-group col-md-6"> <label for="redirect_url">redirect_url</label> <input type="text" class="form-control" id="redirect_url"> </div> <div class="form-group col-md-6"> <label for="email">Email</label> <input type="email" class="form-control" id="email" placeholder="Email"> </div> <div class="form-group col-md-6"> <label for="API_Key">API_Key</label> <input type="text" class="form-control" id="API_Key"> </div> <div class="form-group col-md-6"> <label for="apiuser">apiuser</label> <input type="text" class="form-control" id="apiuser"> </div> </div> <button type="submit" id="submitform" class="btn btn-primary">Submit</button> </form> I want to collect the HTML form data and send it a JSON payload to the API. I have tried with my code below. Your help will be appreciated. How pushed the api in the action on the form but it gave me an error. Am tried doing it with javescript and its not working ans well. -
Is there a Django way query for this PostgreSQL trigram search query
I'm trying to implement the PostgreSQL trigram similarity search query below in to Django project. SELECT *, word_similarity('foo bar buzz', "table"."search_content") AS ws_rank FROM "table" WHERE "table"."owner_id"={owner_id} AND "table"."search_content" %> 'foo bar buzz' ORDER BY ws_rank DESC, "table"."search_content"; Because of the query is raw type, I can't apply django's prefetch_related method to the query. Is there a model manager method in Django to making queries like this, so I can apply prefetch_related or any other query methods. -
Django Aggregation: Summation of Multiplication of two related fields
This is my model: class Inventory(models.Model): product = models.ForeignKey("product.Product", null=True, blank=True, on_delete=models.SET_NULL) count = models.IntegerField(default=1) I basically want to get the sum of product__cost * count for all rows. I would normally do: Inventory.objects.all().aggregate(sum=Sum(F('fieldA') * F('fieldB')))['sum'] but running this with product__cost as fieldA gives me integer out of range. How do I achieve this result correctly? -
File Storage Django - AttributeError: 'bytes' object has no attribute '_committed'
I am attempting to store a PDF as bytes into a Django FileField and I am getting an error: AttributeError: 'bytes' object has no attribute '_committed' I am having issues figuring out what I need to be converting the file to before I save it. Here is my model: def income_certification_upload_path(instance, filename): if instance.resident: # recertification, use resident directory = f'{instance.client_url}/{instance.resident.property.name}/Renewals/Recertification/{instance.id}_{filename}' else: # is initial, use the application directory = f'{instance.client_url}/{instance.resident.property.name}/Renewals/Initial/{instance.id}_{filename}' return directory class IncomeCertification(SafeDeleteModel): _safedelete_policy = HARD_DELETE id = models.AutoField(primary_key=True) client_url = models.CharField(max_length=50) resident = models.ForeignKey(Resident, null=True, blank=True, on_delete=models.SET_NULL, db_column='resident_id', related_name='resident_income_certification') application = models.ForeignKey(Application, null=True, blank=True, on_delete=models.SET_NULL, db_column='application_id', related_name='application_income_certification') status = models.NullBooleanField(choices=[[None, 'Undecided'], [True, 'Accept'], [False, 'Reject']]) decided_by = models.ForeignKey('users.CustomUser', null=True, blank=True, on_delete=models.SET_NULL, db_column='decision_by', related_name='income_certification') file = models.FileField(upload_to=income_certification_upload_path) date_entered = models.DateTimeField(auto_now_add=True, editable=False) last_update = models.DateTimeField(auto_now=True) This is how I am trying to save the file: ... print(type(pdf)) # bytes IncomeCertification.objects.create(file=pdf) -
How can make an autoincrement field in django model which is incrementing not globally but acording to another collumn?
I need to create Django model for logging tasks from Celery. To display this log i assume a need to know the order of the log messages, therefore i should probably have these fields Some PK Celery task ID order of the message the message Is is somehow possible to make the field "order" autoincrement, but so it autoincrements only in the "celery task ID" independently..? I mean.. I will run script with ID 42 and logg messages taks_id: 42, order: 0, message: "just started" taks_id: 42, order: 1, message: "running" taks_id: 42, order: 2, message: "finished" but i can have many task_ids in the database.. and i do not want to fill in always the order of the message Thanks -
What does sys.stdout do
I was going through some code and came across this: f = open("basic.json", 'w') sys.stdout = f f.close() What is happening here? In particular, sys.stdout = f, what does this statement do? Sorry, I'm new to python. -
TypeError: post() got an unexpected keyword argument
I am trying to create a simple blog where I can communicate with the users directly. Each user will have a blog post each month posted by the Admin, and they can comment on it to communicate. The workflow is as follows: Admin logs into the site -> Admin is presented with all the available Users. -> Admin clicks on a User -> If that user has a post for current month, display that post -> Else create new post. Here is what I have: blog/urls.py: from django.urls import path from .views import MessageThread, CreateThread urlpatterns = [ path('user_thread/<int:user_id>', MessageThread.as_view(), name='message_thread'), path('create_thread/<int:user_id>', CreateThread.as_view(), name='create_thread'), ] blog/models.py: from django.db import models from django.contrib.auth.models import User class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField(max_length=9001) posted_for = models.ForeignKey(User, related_name='posted_for', on_delete=models.CASCADE) published_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.title blog/forms.py: from django.forms import models from .models import Post class CreateThreadForm(models.ModelForm): class Meta: model = Post fields = ['title', 'text'] blog/views.py: from .forms import CreateThreadForm from django.shortcuts import render, redirect from django.views.generic import TemplateView from datetime import datetime from django.contrib.auth.models import User class CreateThread(TemplateView): template_name = 'blog/create_thread.html' def get(self, request, *args, **kwargs): return render(request, self.template_name, {'form': CreateThreadForm(), 'user_id': self.kwargs['user_id']}) def post(self, … -
Search Filter for React Redux Django
How to implement a Search Filter list using react-redux on front-end and django as a backend ? Here is my main file <div> <SearchBar/> <ListView/> </div> The SearchBar is handleFormSubmit = e => { e.preventDefault(); const name = e.target.elements.name.value; const age = e.target.elements.age.value; const height = e.target.elements.height.value; console.log(name, age, height) }; render() { return ( <div> ... </div> } The ListView is class ListView extends Component { state = { info: [] }; componentDidMount() { axios.get("http://127.0.0.1:8000/api/") .then(res => { this.setState({ info: res.data }); console.log(res.data); }) } render() { return ( <div> <table rows={this.state.info}/> </div> ); } } export default ListView; The Action is export const Search_Results = results => { return { type: actionTypes.SEARCH_RESULTS, results: results } }; The Reducer is const searchResult = (state, action) => { return updateObject(state, { search: action.results }); }; const reducer = (state = initialState, action) => { switch (action.type) { case actionTypes.SEARCH_RESULTS: return searchResult(state, action); default: return state; } }; export default reducer; The updateObject simply code: export const updateObject = (oldObject, updatedProperties) => { return { ...oldObject, //create clone of old object ...updatedProperties //replace the objects that have the same position with the values/keys from the new method } }; I am … -
How to deal with jsonb object with django admin
I have a model class that extends model.Model. In my model, I have some jsonb fields. How to represent and save those data in django admin? Here is my model class Organization(models.Model): organization_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) is_active = models.BooleanField(default=True) primary_address = models.TextField(null=False) secondary_address = models.TextField(null=True, blank=True) image = models.ImageField(null=True) additional_info = JSONField(null=True, encoder=JSONEncoder) country_code = models.CharField( max_length=10, default='BGD', validators=[RegexValidator("^[A-Z]*$", "only uppercase is allowed")] ) operational_areas = JSONField(null=True, encoder=JSONEncoder) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) How to represent anonymous keys from additional_info as input and value? -
having trouble in saving form data into ManyToMany field
My Model is like class Dish(models.Model): names = models.ManyToManyField(DishName) restaurant = models.ManyToManyField(Restaurant) And My view file is like def AddDish(request): if request.method == 'POST': dishname = request.POST.get('name') res = request.POST.get('restaurant') restaurant = Restaurant.objects.get(id=res) r = Dish(generic_name=GenericName, names=dishname, restaurant=restaurant, ) r.save() And when I try to add my values to Dish model this error occue Direct assignment to the forward side of a many-to-many set is prohibited. Use restaurant.set() instead. I tried to use set but Didnt get where to use this like I tried restaurant.set(r) but no luck till now . Any help would be highly appreciated . thanks in advance -
How to test database cache functionality in django-rest-framework
What is the standard way to test the functionality of a database configured cache (for example django_redis) on django-rest-framework? I've tried the methods in this link to override the settings for my test to configure a cache but this doesn't seem to work with APIClient.client.get from django rest framework. Is is even possible to test a database configured cache? -
notify_user(user.id,repeat=2,repeat_until=None) NameError: name 'user' is not defined
kindly help urgently. i was reading about django-background-tasks and I came across this: https://django-background-tasks.readthedocs.io/en/latest/ i followed the instructions and installed all the requirements but i got this: notify_user(user.id,repeat=2,repeat_until=None) NameError: name 'user' is not defined. -
Django Literally ignores model field
So, I came across this when I was working on a project. I had mistakenly placed a "," after a field in one of my models and Django did all the migrations while ignoring that particular field. It took me a while to realize that a little "," after the field is responsible for my field not being reflected in the database. However, I understand that there shouldn't be a coma but I was king of expecting Django to give me an error or at least a warning. Something like maybe: "Invalid syntax in models.py near FieldName" But it ignores that particular field and keeps on migrating. My question is why does Django let that happen? Is this the expected behaviour and shouldn't Django notify for such things? or why this is being passed silently. Here is an example to have a look at. class person(models.Model): name = models.CharField(max_length=10) surname = models.CharField(max_length=10), age = models.PositiveIntegerField() Now, if you create migrations and apply them Django will simply ignore the surname field here and apply the migrations without any errors, why is it so? -
Dynamicaly display selected option from Django form using jQuery
i have Django html form like this: <form class="form-horizontal" method="POST" action="." enctype="multipart/form-data"> <div class="form-group"> <label class="control-label col-sm-2">Task</label> <div class="col-sm-3"> <select class="form-control" name="task_name" id="task_name"> <option value="" hidden>Select</option> {% for item in tasks %} <option>{{item.task_name}}</option> {% endfor %} </select> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-5 submit"> <button type="submit" class="btn btn-primary" value="Add" name="save">Save</button> </div> </div> </form> where items contains dictionary data. I need to dynamically create few lines of html code that contain data for selected item. For now i can only get selected text value. But it is not displayed dynamically after selection. My jQuery: <script type="text/javascript"> $(function show(){ var txt = $("#task_name").val(); $('#txt_name').val(txt); }); </script> destination: <p id="txt_name"/> Thank you for your time. -
dynamic query builder function
my dynamic query builder function return error AttributeError: 'str' object has no attribute 'objects' my function code is def dynamic_query(model,fields,types,values,operator): ...: from django.db.models import Q ...: ...: queries =[] ...: for (f,t,v) in zip(fields,types,values): ...: if v != "": ...: kwargs = {str('%s__%s' % (f,t)): str('%s' % v)} ...: queries.append(Q(**kwargs)) ...: if len(queries) > 0: ...: q = Q() ...: for query in queries: ...: if operator =="and": ...: q = q & query ...: print(q) ...: elif operator =="or": ...: q = q | query ...: print(q) ...: else: ...: q = None ...: ...: if q: ...: print(q) ...: return model.objects.filter(q) ...: ...: else: ...: return {} i want to build dynamic query in django -
Context Variable renders the previous value upon refresh
I have created a form that accepts a file upload and fetches some interesting data from the file upon POST. However, upon refreshing the page, the form is back to its initial state but the data from the previous file remains. How do I fix it? Here's my code: forms.py choices = (('all', 'all'), ('one', 'one')) class TicketDetailForm(forms.Form): file = forms.FileField() type = forms.ChoiceField(choices=choices) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) views.py def home(request): detail = [] if request.method == 'POST': form = TicketDetailForm(request.POST, request.FILES) if form.is_valid(): if form.cleaned_data['type'] == 'all': file = form.cleaned_data['file'].read() detail.append([str(file, 'utf-8')]) # more workaround with the file else: form = TicketDetailForm() return render(request, 'home.html', {'form': form, 'detail': detail}) home.html {% extends 'base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <p>{{form.as_p}}</p> <input type="submit" value="Submit"/> </form> {% if detail %} <div class="row"> <p>The detail is as follows:</p> {% for d in detail %} {{ d }} {% endif %} </div> {% endif %} {% endblock %} -
django.db.utils.IntegrityError: UNIQUE constraint failed: authtoken_token.user_id
I'm new in django rest framework and I'm trying do unit test using Token for my api, but it kept throwing IntegrityError. I've reseached many blog to find the solution but couldn't find. Please help me solve this. Thank in advance. Here is the code that I've tried from django.contrib.auth.models import User from rest_framework.test import APITestCase, APIRequestFactory, force_authenticate from rest_framework.authtoken.models import Token from myapp.api.views import UserViewSet class UserTestCase(APITestCase): def setUp(self): self.superuser = User.objects.create_user(username='superuser', email='uid.sawyer@gmail.com', password='superuser', is_staff=True) self.factory = APIRequestFactory() self.token = Token.objects.create(user=self.superuser) self.token.save() def test_list(self): request = self.factory.get('/api/users/') force_authenticate(request, user=self.superuser, token=self.token) response = UserViewSet.as_view({'get': 'list'})(request) self.assertEqual(response.status_code, 200) -
Makemigrations in Django
I cannot "makemigrations" in my Django project. When I try to do "python manage.py makemigrations" It shows the following Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/ani/Desktop/Backup/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/ani/Desktop/Backup/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ani/Desktop/Backup/venv/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/ani/Desktop/Backup/venv/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/ani/Desktop/Backup/venv/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/ani/Desktop/Backup/venv/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 89, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/home/ani/Desktop/Backup/venv/lib/python3.7/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/ani/Desktop/Backup/venv/lib/python3.7/site-packages/django/db/migrations/loader.py", line 273, in build_graph raise exc File "/home/ani/Desktop/Backup/venv/lib/python3.7/site-packages/django/db/migrations/loader.py", line 247, in build_graph self.graph.validate_consistency() File "/home/ani/Desktop/Backup/venv/lib/python3.7/site-packages/django/db/migrations/graph.py", line 243, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/home/ani/Desktop/Backup/venv/lib/python3.7/site-packages/django/db/migrations/graph.py", line 243, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/home/ani/Desktop/Backup/venv/lib/python3.7/site-packages/django/db/migrations/graph.py", line 96, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration djoser.0001_initial dependencies reference nonexistent parent node ('auth', '0011_update_proxy_permissions') I tried installing mysqlclient and creating the database all over again but then it doesn't work at all. -
Django-admin is not working on Windows 10
I am new in django, and now I want to run django to start my project but django-admin startproject mywebsite just working on this path C:\Users\sasa\AppData\Local\Programs\Python\Python37-32\Scripts I have added this path on my enviornment PATH,and python is working everywhere on cmd.How can I solve it? -
DRF filter issues
I am having issues on filtering objects in Django. I have the following model. class Category(TimeStamp): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True, blank=True) parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) as it can be seen from the code. I have Category objects such as Electronics inside Electronics there is again sub category like Phones and inside of Phones there is Smartphones category. views.py class CategoryView(generics.ListCreateAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer lookup_field = 'slug' name = 'category-list' filter_class = CategoryFilter filters.py class CategoryFilter(FilterSet): parent = NumberFilter(field_name='parent', lookup_expr='id__exact') class Meta: model = Category fields = ['parent'] this is working but not as expected because I search parent=0 It returns all Category like Electronics and If I search parent=1 it returns all sub category. But I do not need to do this When I search parent=1 it should return all sub categories and sub parents Electronics > Phones > Cell Phones How Can I get all objects with one query any help please) I am new here please if anything is unclear. Let me know. I will try to explain in more detail.