Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
redirect Createview to Updateview if record exist in 1:1
I am trying to redirect a logged in user to an Updateview instead of a Createview if they have already created a record in the oranizations model. My organizations has a 1:1 relationship with my users model. I am currently able to return the Updateview with the get method if the related record exists, but the Url is not redirected to /update My code: urls.py urlpatterns = [ path("add/", view=organization_add_view, name="add"), path("update/", view=organization_update_view, name="update"), path("<int:id>/<str:slug>", view=organization_detail_view, name="detail"), ] models.py class Organization(TimeStampedModel): name = CharField(_("Organization Name"), blank=False, max_length=255, unique=True) slug = AutoSlugField(_('slug'), max_length=100, unique=False, populate_from=('name',)) user = OneToOneField(settings.AUTH_USER_MODEL, on_delete=CASCADE, db_index=True) def __str__(self): return self.name views.py class OrganizationDetailView(DetailView): model = Organization slug_field = "slug" slug_url_kwarg = "slug" organization_detail_view = OrganizationDetailView.as_view() class OrganizationAddView(LoginRequiredMixin, CreateView): model = Organization form_class = OrganizationForm def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user obj.save() return self.get_success_url() def get(self, *args, **kwargs): # this works for getting me the update view but URL is still /add if self.model.objects.get(user=self.request.user): return OrganizationUpdateView.as_view()(self.request, *args, **kwargs) else: return super(OrganizationAddView.as_view()(self.request, *args, **kwargs)) def get_success_url(self): return reverse("organizations:list") organization_add_view = OrganizationAddView.as_view() class OrganizationUpdateView(LoginRequiredMixin, UpdateView): model = Organization form_class = OrganizationForm def get_object(self, queryset=None): obj = self.model.objects.get(user=self.request.user) return obj def get_success_url(self): return reverse("organizations:update") organization_update_view = OrganizationUpdateView.as_view() -
Django form field populated with AJAX is not binding
I have a form for user to search based on grade, subject and year. The grade fields prepopulated at initialization while subject and year are populated based on the grade selection for subject and subject selection for year. I managed to accomplish that using AJAX request and it works perfectly. index view process the form and if valid send the parameters to another view. However, nothing happens when the search button is clicked. Thanks in advance in form.py class SearchForm(forms.Form): grade = forms.ModelChoiceField( queryset =Grade.objects.all(),to_field_name="grade",required=False) subject = forms.ModelChoiceField(queryset=Subject.objects.none(), required=True ) year = forms.ModelChoiceField( queryset=Exam.objects.none(), required=True ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) index.html <form id="searchForm" action="" method="POST" data-url-types="{% url 'exam:subjects_choices' %}" data-url-years="{% url 'exam:years_choices' %}" novalidate> {% csrf_token %} <div class="row"> <div class="col-xs-6"> {{ form.grade}} </div> <div class="col-xs-12"> {{ form.subject}} </div> <div class="col-xs-6"> {{ form.year }} </div> </div> <button class=" type="submit">Search</button> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_grade").change(function () { var urlSubjects = $('#SearchForm').attr('data-url-subjects'); var gradeId = $(this).val(); console.log(urlSubjects); console.log(gradeId); $.ajax({ statusCode: { 404: function() { alert( "page not found" ); } }, url: urlSubjects, data: { grade: gradeId }, success: function(data) { $('#id_subject').html(data); } }); }); $('#id_subject').change(function() { var urlYears = $('#SearchForm').attr('data-url-years'); var subjectId = $(this).val(); var gradeId = $('#id_grade').val(); console.log(urlYears); … -
Django admindocs - simplify_regex yields double forward slash
We have been using simplify_regex function from Django admindocs for a while to generate readable urls for our docs. When upgraded from Django 1.8.7 to Django 1.11.15 we encountered a breaking change in the function - most of our URLs now show up with double forward slashes. Example: urlpattern (concatenated): 'api/^v1//^^some/path/$' old return value: '/api/v1/some/path/' new return value: '/api/v1//some/path/' Is this change intentional? Is this a bug? It looks like the function has drastically changed, I see that ".replace('//', '/')" was removed, not sure why. Old implementation (1.8.7): named_group_matcher = re.compile(r'\(\?P(<\w+>).+?\)') non_named_group_matcher = re.compile(r'\(.*?\)') def simplify_regex(pattern): """ Clean up urlpattern regexes into something somewhat readable by Mere Humans: turns something like "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$" into "<sport_slug>/athletes/<athlete_slug>/" """ # handle named groups first pattern = named_group_matcher.sub(lambda m: m.group(1), pattern) # handle non-named groups pattern = non_named_group_matcher.sub("<var>", pattern) # clean up any outstanding regex-y characters. pattern = pattern.replace('^', '').replace('$', '').replace('?', '').replace('//', '/').replace('\\', '') if not pattern.startswith('/'): pattern = '/' + pattern return pattern New implementation (1.11.15): def simplify_regex(pattern): r""" Clean up urlpattern regexes into something more readable by humans. For example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$" into "/<sport_slug>/athletes/<athlete_slug>/". """ pattern = replace_named_groups(pattern) pattern = replace_unnamed_groups(pattern) # clean up any outstanding regex-y characters. pattern = pattern.replace('^', '').replace('$', '').replace('?', … -
Django - Images won´t displayed in template. but image url showed up. Urls.py Issue?
Using Django 2.1.5 + Bootstrap 4.2 and some Icons from fontawesome Hello , after a long search I decided to post, because most answer are related to older Django versions. I am relatively new to Django and I like to test all the Function/Class Views and Modelfields. Now i wanted to test how i can display images linked with my database in my template. But unfortunately, images want not display, all I see is image placeholder icon. i created a app and 2 simple models, with musicians (with images) and cars. The upload via admin works and the blank url are accessible in the Template via {{ modelone.person_pic }} aquaman / models.py class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) person_pic = models.ImageField(upload_to='artist/', max_length=255, null=True, blank=True ) def __str__(self): return "{} - {}".format(self.first_name[:25], self.last_name[:25]) class Data_Sheet(models.Model): car = models.CharField(max_length=30) color = models.CharField(max_length=30) def __str__(self): return "{} - {}".format(self.car[:25], self.color[:25]) views.py from django.shortcuts import get_object_or_404, render, redirect from django.utils import timezone from django.views.generic.list import ListView from django.views.generic import TemplateView from .models import Person, Data_Sheet <…some other views…> class ArtistView4(TemplateView): template_name = 'aquaman/artistview4.html' def get_context_data(self, **kwargs): context = super(ArtistView4, self).get_context_data(**kwargs) context['modelone'] = Person.objects.all() context['modeltwo'] = Data_Sheet.objects.all() return context artistview4.html {% extends 'base.html' … -
how to get changed data of fullcalendar event to sqlite of django
I can get event information(event.title, event.start...)with 'eventDrop' function. it works fine. However, I want to get these info to my database. would anyone help me out? I think I need to use Ajax to get data but could not get it. Thank you eventDrop: function(event, delta, revertFunc) { console.log(event.title), console.log(event.start.format()) console.log(event.resourceId) }, -
Installing chat package in pycharm
Hi I tried to install chat package for my django project in pycharm and I run the command: pip install chat but I have error: "AttributeError: _DistInfoDistribution__dep_map" I have no idea how to solve this problem could you please help me? -
How do I properly format data in a python POST request to Streamlabs API?
I'm trying to connect our application to Streamlabs' API so we can post donation alerts. To do that, I need to get an access token for the user whose channel we want to alert on. It's a normal OAuth2 thing. We hit the /authorize endpoint and get a code back, which we're then supposed to able to use to get an access token from the /token endpoint (https://dev.streamlabs.com/v1.0/reference#token-1). But when we send the POST request for the token, we get an error saying the request is missing the "grant_type" parameter. We're using the normal requests library. I've tried changing the format of the request to requests.post. I've tried altering the data by wrapping it in urlencode and json.dumps. Still no luck. streamlabs_client_id = config('STREAMLABS_CLIENT_ID') streamlabs_client_secret = config('STREAMLABS_CLIENT_SECRET') streamlabs_redirect_uri = config('STREAMLABS_REDIRECT_URI') grant_type = 'authorization_code' querydict = { "grant_type":"authorization_code", "client_id":streamlabs_client_id, "client_secret":streamlabs_client_secret, "redirect_uri":streamlabs_redirect_uri, "code":code } url = "https://streamlabs.com/api/v1.0/token" streamlabs_response = requests.request("POST", url, data=querydict) this is the json I get back every time: {"error":"invalid_request","error_description":"The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the \"grant_type\" parameter."} Any ideas what i'm doing wrong with the data? -
Django force download file on redirect instead of showing content
Right now I have a download button which when clicked redirects to the page with the file and shows it content. I don't want it to do that. I want it to forcefully download the content to the users device instead of showing it. How do I do that? My current code: def download_item(request, pk): item = get_object_or_404(Usertasks, pk=pk) output_path = item.OutputPath filename = item.TaskID + "_" + item.TaskNavn + "." + item.Taskformat if request.user.id == item.user_id: response = HttpResponse(content_type='application/force-download') response['Content-Type']= 'attachment; filename="{}"'.format(filename) response['X-Accel-Redirect'] = output_path return response if not request.user.id == item.user_id: return redirect('/account/login/') -
Django Rest Framework is owner
I'd like to create a field is_owner for my serializer which would return whether or not the object being serialized is owned by the user making the request. Something like: """Defines Some serializer with an owner""" from rest_framework import serializers class SomeSerializer(serializers.ModelSerializer): """Returns the is_owner field as a boolean""" is_owner = serializers.SerializerMethodField() class Meta: model = SomeModel fields = ('is_owner',) def get_is_owner(self, obj): """Will return True if the requesting user is the owner, else false""" return request.user.id == obj.user.id Is this the way to do it? Should I be passing the request object to the serializer to make this work? Should I be testing this at the view level? Thank you! -
Change other objects inside model's custom save method in django
Well, I have two django models for storing Questions and Questionnaires. Every question is inside a questionnaire. Every Question should have a field to store the order it is going to appear in a questionnaire. My questions is what is about the best way to handle changes in the order of a question. The code have for the models: class Questionnaire(models.Model): name = models.CharField(max_length = 100) time_creation = models.DateTimeField(auto_now=True) class Question(models.Model): questionnaire = models.ForeignKey(Questionnaire, related_name='questions', on_delete=models.CASCADE) text = models.TextField() order = models.IntegerField() One way I thought of doing it was by overriding the save method for the Question model, like that: def save(self, *args, **kwargs): all_questions = self.questionnaire.questions.all() if (self.order == None or self.order > len(all_questions)+1 or self.order == 0): self.order = len(all_questions)+1 # starts in 1 else: previous = all_questions.filter(order=self.order) if len(previous)>0: p = previous[0] p.order = self.order+1 p.save() super().save(*args, **kwargs) It is kind of a recursive function, inside save() i verify if there is a Question with the same order number and increase it then call the save (inside the save), which will do the same for this object. Is it a good way to solve the problem? Django has a few idiosyncrasies that i might not be … -
Subscriber not joining session
I am using OpenTok's video API to create a page that allows two users to video chat. I have been able to create the information needed on the server side to allow a user to publish their stream; however, I am having trouble allowing a subscriber join the stream. I would appreciate any help in altering my code so that a subscriber can join the session. HTML {% load static %} {% block body %} <div id="videos"> <div id="subscriber"></div> <div id="publisher"></div> </div> <link rel="stylesheet" href="{% static 'student/css/app.css' %}" type="text/css" /> <script type="text/javascript"> var apiKey = "{{ api_key }}"; var sessionId = "{{ session_id}}"; var token = "{{ token }}"; </script> <script src="https://static.opentok.com/v2/js/opentok.min.js"> . </script> <script src="{% static 'student/javascript/app.js' %}"></script> {% endblock %} Javascript // Handling all of our errors here by alerting them function handleError(error) { if (error) { alert(error.message); } } // (optional) add server code here initializeSession(); function initializeSession() { var session = OT.initSession(apiKey, sessionId); // Subscribe to a newly created stream session.on('streamCreated', function(event) { session.subscribe(event.stream, 'subscriber', { insertMode: 'append', width: '100%', height: '100%' }, handleError); }); // Create a publisher var publisher = OT.initPublisher('publisher', { insertMode: 'append', width: '100%', height: '100%' }, handleError); // Connect to the … -
Howto get Mailchimp pop-up to work in Chrome
I seem to be having trouble getting the Mailchimp pop-up subscribe function to work on Chrome: I added the following code to my index.html page in django: <script type="text/javascript" src="//downloads.mailchimp.com/js/signup-forms/popup/unique-methods/embed.js" data-dojo-config="usePlainJson: true, isDebug: false"> </script> <script type="text/javascript">window.dojoRequire(["mojo/signup-forms/Loader"], function(L) { L.start({"baseUrl":"mc.us19.list-manage.com","uuid":"4eccd5a19349953c3e023b61d","lid":"9b2e4611ac","uniqueMethods":true}) }) </script> Seems to be working fine in Opera, Firefox and IE but in Chrome I get the following error: Uncaught TypeError: window.dojoRequire is not a function. What am I missing to make this work in Chrome? Additional info: Python 3.6.1 Django 2.1.3 -
How should I structure a tree of multiple model types?
I'm trying to model television shows down to the episode level. Given that each level of the tree (network, series, season, episode) has different fields, I want to use different model types for each level. My initial approach was to keep track of the parent with a foreign key at each level (this is a simplified approach, I know there would be other fields): class Network(models.Model): ... class Series(models.Model): network = models.ForeignKey(Network) ... class Season(models.Model): series = models.ForeignKey(Series) ... class Episode(models.Model): season = models.ForeignKey(Season) ... But if I want to get the network of a specific episode, I have to lookup Episode->Season->Series->Network. That seems inefficient and poorly architected because it requires a lot of queries. I saw the library django-mptt, but this requires that your tree be built of a single model type. From a design standpoint, what's the standard way to structure this type of tree? What are the tradeoffs of different approaches? -
Django: my view enters Try part and also Except part?
I've a View that, according to my prints, enters the Try and the Except parts. As far as I understand, it only should enter the Try part or the Except part not both. Cart object exist Lenght in Cart_Items 1 Enters Except PART 55 Why could this be happening? def cart_detail(request, total = 0, counter = 0, cart_items = None): try: cart = Cart.objects.get(id = request.COOKIES.get("cart_id")) if not cart: print("No Cart object") else: print("Cart object exist") cart_items = CartItem.objects.filter(cart = cart) print("Lenght in Cart_Items") print(len(cart_items)) for cart_item in cart_items: total += (cart_item.product.price) sample_items = SampleItem.objects.filter(cart=cart) for sample_item in sample_items: total += (sample_item.sample.price) culqi_my_public_key = settings.CULQI_PUBLISHABLE_KEY #Es necesario mandar la llave pública para generar un token culqi_total = int(total * 100) #El total para cualqui debe multiplicarse por 100 categories = Category.objects.exclude(name='Muestras') return render(request, 'cart.html', dict(cart_items = cart_items, sample_items = sample_items, total = total, counter = counter, culqi_total = culqi_total, culqi_my_public_key = culqi_my_public_key, categories = categories)) except: print('Enters Except PART') print(request.COOKIES.get("cart_id")) categories = Category.objects.exclude(name='Muestras') return render(request, 'cart.html', {'categories':categories}) -
I'm trying now to hook up my postgres database but am a little unfamiliar with where I should place my db information
as it is using a little different syntax than I am used to seeing. In my base.py settings file: DATABASES = { 'default': env.db('DATABASE_URL', default='postgres://project'), } Where do I place the typical database info like User, Host, Password, etc? In the section above in base.py or overide it in local.py settings file? As is, I've created the database in postgres using the same slug name in cookiecutter project setup but I'm getting a django.db.utils.OperationalError: fe_sendauth: no password supplied. PS: I'm using windows 10 and wonder if it could have something to do with the pg_hba.conf file? Something about setting a value to trust for local? -
OSError at /en/account/login/
I've been trying to put Saleor/eCommerce web site running on Digital Ocean, and i keep geting this error all the time, even thoug i've read all the docs and did everything right. I fallowed all the docs from here and all the Saleor docs for the installation. I installed all the latest versions of npm, yarn etc. And still, i keep getting this error : Error reading /home/saleordeploy/saleor_project/saleorecommerce/webpack-bundle.json/webpack.config.js. Are you sure webpack has generated the file and the path is correct? Request Method: GET Request URL: http://157.230.28.22:8000/en/account/login/?next=/en/account/ Django Version: 2.1.5 Exception Type: OSError Exception Value: Error reading /home/saleordeploy/saleor_project/saleorecommerce/webpack-bundle.json/webpack.config.js. Are you sure webpack has generated the file and the path is correct? Exception Location: /home/saleordeploy/saleor_project/myvenv/lib/python3.5/site-packages/webpack_loader/loader.py in _load_assets, line 32 Python Executable: /home/saleordeploy/saleor_project/myvenv/bin/python Python Version: 3.5.2 Python Path: ['/home/saleordeploy/saleor_project/saleorecommerce', '/home/saleordeploy/saleor_project/myvenv/lib/python35.zip', '/home/saleordeploy/saleor_project/myvenv/lib/python3.5', '/home/saleordeploy/saleor_project/myvenv/lib/python3.5/plat-x86_64-linux-gnu', '/home/saleordeploy/saleor_project/myvenv/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/home/saleordeploy/saleor_project/myvenv/lib/python3.5/site-packages', '/home/saleordeploy/saleor_project/saleorecommerce'] Server time: Wed, 6 Feb 2019 10:34:33 -0600 -
Django Development Cross-Origin Read Blocking (CORB) (not CORS)
I am trying to test a call to my local Django development server. This is an AJAX call that returns a JSON object. The Django view does this: return JsonResponse(response, safe=False) I test this by launching the Django server (which runs the back end) and then launching my browser and opening the HTML page I have modified. These pages are not served by Django. In Firefox, I can make the ajax call on the page. It returns the correct data, with the correct MIME type. In Chrome, I can not. I get the following error: Cross-Origin Read Blocking (CORB) blocked cross-origin response http://localhost:8000/dataload/alljson with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details. I have tried to search for the solution to this problem. I've checked this question, but the suggestion to clear my cache doesn't do anything. I've also found suggestions that involve using django-cors-headers, but this is CORB (not CORS). Nonetheless, I've installed corsheaders and set CORS_ORIGIN_ALLOW_ALL = True to eliminate that as a possibility. Still no dice. How can I get Chrome to allow the response from my development Django server for this ajax call? -
Django form: multiple form inheritance
I've got few django form classes like these ones: class MyCleaningClassForm(forms.Form): def clean(self): super(MyCleaningClass, self).clean() cleaned_data = {} for key, value in self.cleaned_data.items(): if value: cleaned_data[key] = value return cleaned_data class MyDataForm(forms.Form): data1 = forms.Charfield(max_length=123) data2 = forms.IntegerField() def clean(self): cleaned_data = {} if self.cleaned_data['data1'] == 'lala' \ and self.cleaned_data['data2'] == 'lili': cleaned_data['data1'] = 'lolo' return cleaned_data def fill_up_data_dict(self, cleaned_data): data_dict = {} data_dict['data1'] = cleaned_data['data1'] data_dict['data2'] = cleaned_data['data2'] return data_dict class MySubDataForm(MyDataForm, MyCleaningClassForm): other_data = forms.IntegerField() def clean(self): # I want this line to call both clean methods from the 2 superclass super(MySubDataForm).clean() self.cleaned_data['my_data_dict'] = self.fill_up_data_dict( self.cleaned_data) return self.cleaned_data MyCleaningClass is a class I use in several other forms. It takes off all the fields that are empty from cleaned_data. MyDataForm is a class I use in several other forms as well. This one helps me filling a data_field in a dictionary as request.POST is flat. It handles some fixed fields. How should I do? Is there anything better than: cleaned_data = MyDataForm.clean(self)? Moreover, I'm not sure how to modify self.cleaned_data. I know both ways are acceptable (from the django doc) but should I do cleaned_data = self.cleaned_data just before the return statement? How would you do it all? … -
Django model foreign key filtering on integer issue
I have a Building model with an integer field indicating the type of building: class Building(models.Model): building_type = models.PositiveIntegerField('Building Type') I have a BuildingUnit model with a foreign key reference to Building: class BuildingUnit(models.Model): building_fk = models.ForeignKey( 'Building', on_delete=models.CASCADE, verbose_name="Building" ) I am overriding the BuildingUnit model's init function and attempting to filter the foreign keys based on an integer value (the type of building it is): self.base_fields['building_fk'].queryset = BuildingUnit.objects.filter (building_fk__building_type=16) It does not work. All building types continue to come back. When I debug and inspect the SQL statement, it says invalid syntax. The WHERE clause says building.building_type=16. It looks right to me. I'm using Postgres. How do I make objects.filter() in Django evaluate an integer properly in PLPGSQL? I've exhausted looking at all examples of how to get this done. Plz help. -
create all table models using indpectdb in django
I have a database "Employee" into SQL-Server-2016 , which contains a lot of tables such as: dbo.Employee dbo.Department dbo.Salary dbo.Country dbo.Address domain1\userId.auth_group_permissions domain1\userId.auth_user domain1\userId.django_session domain1\userId.auth_permission ...... I have tried to generate database in tables in django models by using: python manage.py inspectdb>models.py but only django models generated such as AuthUserGroups, AuthUserUserPermissions, DjangoAdminLog,... What should i have do , to generate all dbo schema tables models? -
ImportError: No module named filebrowser in Django 1.11
I write pip install django-filebrowser and get: Requirement already satisfied: django-filebrowser in /media/m0nte-cr1st0/43338d5a-aa90-411c-a6d7-96964c46e415/m0nte-cr1st0/programming/startapp/myvenv/lib/python3.5/site-packages (3.11.1) Requirement already satisfied: django-grappelli<2.13,>=2.12 in /media/m0nte-cr1st0/43338d5a-aa90-411c-a6d7-96964c46e415/m0nte-cr1st0/programming/startapp/myvenv/lib/pyt If I write python manage.py makemigrations, I get error Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/m0nte-cr1st0/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/m0nte-cr1st0/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/home/m0nte-cr1st0/.local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/m0nte-cr1st0/.local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/m0nte-cr1st0/.local/lib/python2.7/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named filebrowser Python2.7, Django1.11.8 -
Serialize a Django model's field definiton
I have a very complicated model whose definition I use to build a dynamic webpage. I retrieve this definition by doing a Django Rest Framework OPTIONS call on the ModelViewSet. This is what is returned by an OPTIONS call on my ModelViewSet. Inside of POST, inside of actions, is a serialized version of my model. I'm running into a problem where I have a User type who is not allowed to POST on this ModelViewSet, thus causing the OPTIONS call to not include POST inside of actions. This is what it looks like for that user type. This causes my webpage to fail to render. In hindsight, building my webpage off of this OPTIONS call was a poor call and I would like to pivot away from that. I'm searching for a way to 'serialize' my model, like Django Rest Framework had in actions.POST. Would anyone know where to start? -
Django newbie error: NotImplementedError: subclasses of BaseDatabaseClient must provide a runshell() method
I'm newbie in django&co world... these last few days it was working the dbshell but I don't really know what I touched because it is producing it to crash... I would be greatfull for any clue. Attaching the error. I'm trying to make a rest API with django, mongodb connected by djongo. (DjangoProject) C:\Users\Skootik\alchemyml_services>python manage.py dbshell Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\Skootik\Anaconda3\envs\DjangoProject\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Skootik\Anaconda3\envs\DjangoProject\lib\site-packages\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Skootik\Anaconda3\envs\DjangoProject\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Skootik\Anaconda3\envs\DjangoProject\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\Skootik\Anaconda3\envs\DjangoProject\lib\site-packages\django\core\management\commands\dbshell.py", line 22, in handle connection.client.runshell() File "C:\Users\Skootik\Anaconda3\envs\DjangoProject\lib\site-packages\django\db\backends\base\client.py", line 12, in runshell raise NotImplementedError('subclasses of BaseDatabaseClient must provide a runshell() method') NotImplementedError: subclasses of BaseDatabaseClient must provide a runshell() method -
Restrict Groups in django admin for staff user
I am trying to restrict the groups populated for staff users, such that a user X( staff ) is able to view and edit only those groups which X is a member. I am able to filter groups populated on admin/auth/group/ by registering the new class. class RestrictGroupAdmin(GroupAdmin): def get_queryset(self, request): if request.user.is_superuser: return super(RestrictGroupAdmin, self).get_queryset(request) return request.user.groups.all() With this approach I am able to filter out groups on admin/auth/group/, but unable to filter out the list of available groups in user edit admin page . Is there a way to filter the available groups in user edit page? Also, is the above approach to restrict groups is correct ? Can we extend the same approach to users and permissions as well ? PS: Django version 1.11.1 -
Unsupported lookup 'incontains' for CharField or join on the field not permitted
I am getting below Error while writing the Django ORM queryset : Unsupported lookup 'incontains' for CharField or join on the field not permitted I have tried the mentioned code to retrieve the query set product = Clothing.objects.filter(Q(product = Product.objects.filter(name__icontains =question).first())|Q(brand__icontains = question)| Q(category__icontains = question) | Q(sub_category__incontains = question) | Q(description__icontains = question)) I expect the Output Query should return the ouptut but the actual output is "Unsupported lookup 'incontains' for CharField or join on the field not permitted"