Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Form will not show in Django
So I am trying to show a dropdown menu with Django 2.x (latest version) for an ecommerce site that allows you to select the quantity of an item before adding to cart but the quantity form is not showing. I have a shop app and a cart app and the form is in the cart app. Here is what it looks like: No quantity drop down menu is showing How do I get it to show? html <form action="{% url "cart:cart_add" product.id %}" method="post"> {% csrf_token %} {{ cart_product_form }} <input type="submit" value="add to cart" class="btn btn-primary"> </form> Here is what the dev tools looks like: Dev Tools for the form shop views.py from django.shortcuts import render, get_object_or_404 from .models import Category, Product from cart.forms import CartAddProductForm from django.template import RequestContext def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=category) context = { 'category': category, 'categories': categories, 'products': products } return render(request, 'shop/product/list.html', context) def product_detail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) cart_product_form = CartAddProductForm() context = { 'product': product, 'cart_product_form': cart_product_form } return render(request, 'shop/product/detail.html', context) shop urls.py from django.conf.urls import re_path from . import … -
How to pass multiple queries in url to Django
my urls.py setting is path('somepath', views.somefunc.as_view(), name='SomeFunc') SomeFunc takes POST and is supposed to take some query commands like localhost:8000/path/to/somepath?a=f&b=g When I print out the request itself, it seems like it's only reading POST /path/to/somepath?a=f and I cannot get anything from request.POST How do I read both a and b? This is Django2.0 by the way -
UpdateView along with updating another model fields?
class FootballUpdate(UpdateView): model = Football fields = ['date', 'time', 'duration', 'category', 'place', 'game_status', 'event', 'score_team1', 'score_team2', 'team1', 'team2', 'game_level'] template_name_suffix = '_update_form' success_url = reverse_lazy('index') def post(self, request, pk): match = Football.objects.get(pk=pk) team1 = match.team1 team2 = match.team2 score_team1 = match.score_team1 score_team2 = match.score_team2 if score_team1 > score_team2: football_score = FootballScore.objects.filter(team=team1)[0] football_score.win = football_score.win + 1 football_score.save() return HttpResponse('Score Successfully Updated! Team1 won!') else: football_score = FootballScore.objects.filter(team=team2)[0] football_score.win = football_score.win + 1 football_score.save() return HttpResponse('Score Successfully Updated! Team2 won!') ------------------------------------------------------------------------ class Football(Match): score_team1 = models.IntegerField(default='-1') score_team2 = models.IntegerField(default='-1') team1 = models.ForeignKey(Team, related_name='team1_football', on_delete=models.CASCADE, null=True) team2 = models.ForeignKey(Team, related_name='team2_football', on_delete=models.CASCADE) game_level = models.CharField(max_length=256, null=True, choices=LEVEL_CHOICES) # like semi-final, final etc # connect = models.ForeignKey(Match, on_delete=models.CASCADE) def __str__(self): return str(self.game_level) class FootballScore(models.Model): team = models.ForeignKey(Team, related_name='teams', on_delete=models.CASCADE) win = models.IntegerField(default='0') My Sport is Football with its usual fields, Now i am making Football score to update win field of Teams. As you can see, i have previously made UpdateView for Football model , Now i am making changes to it to add my new requirements of incrementing win field, Previously updateView was working fine, after adding "win" field, my win field in incrementing fine but update filed is not working. Thanks. -
QuerySet .values() method positional arguments are suddenly required?
> python manage.py shell Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from api.models import Listing >>> Listing.objects.all().values() Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: values() missing 2 required positional arguments: 'fields' and 'expressions' The Django 2.1 documentation for values() pretty clearly states both 'fields' and 'expression' arguments are optional, so what gives? I'm having the same issue with all my models (even django.contrib.auth.models.User) -
How to call Python functions from JavaScript in Django?
I've been struggling on this for a couple days. I've read through many posts, blogs, and watch video demo on Django projects, but nothing quite answers my problem. I have a Django webapp that uses a Python API to connects to a third-party service to analyze text data. The user writes into a text area, presses the button, then the text is sent to the service which returns a list of JSON objects. The API call to this service is a Python function. I'm trying to use Ajax to make an async call to the Python function using the text data as a param when the button is pressed. I'm not at this time trying to invoke my third-party service, yet. I'm just trying to see if I can get a response from Python sending input and receiving output. Most of the examples I've found involve creating a form and submitting it so the Django framework automatically calls it's Python functions. A form is not exactly what I'm trying to build, nor am I wanting to proceed to a new page to see the results or refresh the current one. <!-- index.html --> <html> <head> <title>Test Data</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script> … -
while installing mysqlclient in django i got Following Error
Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz Installing collected packages: mysqlclient Running setup.py install for mysqlclient: started Running setup.py install for mysqlclient: finished with status 'error' Complete output from command C:\Users\jaswitha\PycharmProjects\FirstProj\venv\Scripts\python.exe -u -c "import setuptools, tokenize;file='C:\Users\jaswitha\AppData\Local\Temp\pycharm-packaging\mysqlclient\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\jaswitha\AppData\Local\Temp\pip-5mltk4fj-record\install-record.txt --single-version-externally-managed --compile --install-headers C:\Users\jaswitha\PycharmProjects\FirstProj\venv\include\site\python3.6\mysqlclient: C:\Users\jaswitha\AppData\Local\Programs\Python\Python36\lib\distutils\dist.py:261: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running install running build running build_py creating build creating build\lib.win-amd64-3.6 copying _mysql_exceptions.py -> build\lib.win-amd64-3.6 creating build\lib.win-amd64-3.6\MySQLdb copying MySQLdb__init__.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\compat.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.6\MySQLdb creating build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants__init__.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.6\MySQLdb\constants warning: build_py: byte-compiling is disabled, skipping. running build_ext building '_mysql' extension creating build\temp.win-amd64-3.6 creating build\temp.win-amd64-3.6\Release C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,3,13,'final',0) -D__version__=1.3.13 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include" -IC:\Users\jaswitha\PycharmProjects\FirstProj\venv\include -IC:\Users\jaswitha\AppData\Local\Programs\Python\Python36\include -IC:\Users\jaswitha\AppData\Local\Programs\Python\Python36\include /Tc_mysql.c /Fobuild\temp.win-amd64-3.6\Release\_mysql.obj /Zl _mysql.c _mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\bin\\cl.exe' failed with exit status 2 ---------------------------------------- Command "C:\Users\jaswitha\PycharmProjects\FirstProj\venv\Scripts\python.exe … -
If uploaded, direct to different page django
I'm creating a webpage that will receive uploaded file then direct it to a different page if the upload is successful. However, return httpresponseredirect doesnt work, i'm having issues with directing it to a different page, im using django. Here is uploadOne.html {% extends 'base.html' %} {% load static %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% if uploaded_file_url %} **return HttpResponseRedirect("http://localhost:8000/uploads/uploadTwo/")** {% endif %} {% endblock %} in the urls.py, here is my urlpattern code urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^uploads/uploadOne/$', views.uploadOne, name='uploadOne'), url(r'^uploads/uploadTwo/$', views.uploadTwo, name='uploadTwo'), url(r'^admin/', admin.site.urls), I know that the code that im looking for should go to the bolded area but i dont know how to put the proper code, if anyone can help me, that would be great -
django test server error: connection refused. How to deploy apps locally to test?
This is the first time I've developed a web app using Django and one of my first major attempts at programming. I'm trying to deploy my project to the django test server- http://127.0.0.1:8000/ -but I get an error that says the connection is refused. I've looked through Django's documentation and and other websites about django deployment but I'm at a loss on how to troubleshoot this error. If someone can recommend a way for me to deploy django locally so I can test my web app using django test server or recommend another deployment service that is easy for new programmers to use that would be very appreciated. Davis Joseph. -
Static_Root in settings.py redirecting to my static folder in app instead of base root
I am having a hard time deploying a project to heroku, because it says it cannot find the static files. My static files are in an app called 'social' in a folder called 'static', they aren't in the base directory where manage.py is. --p_12 (folder)- settings.py --social (folder) -static (folder) - css, images, javascript --manage.py The heroku docs says to put this in your settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) So my question, how do I get this to point to my static folder in my social app. I've honestly tried for like an hour on this. Thanks for your help. -
Django DEBUG weirdness in IIS: DEBUG=False still runs in debug mode
Summary: My site is running in DEBUG mode even though settings are set to DEBUG = False. FYI, I've researched this and found some excellent responses and testing ideas in these related questions (none of which helped, even though logically they SHOULD have): django DEBUG=False still runs in debug mode and Heroku Django DEBUG Setting not applied IIS FastCGIHandler environmental variable: Name = DJANGO_DEBUG Value = False Note: Removing this environmental variable causes a 500 error regardless of setting in production.py. settings/production.py: Different scenarios tried in settings/production.py using env variable set to False in my FastCGIHandler: DEBUG = os.environ.get('DJANGO_DEBUG', False) RESULT: Site runs in Debug Mode DEBUG = bool(os.environ.get('DJANGO_DEBUG', False)) RESULT: Site runs in Debug Mode DEBUG = False (hardcode w/o env var) RESULT: Site doesn't work, returns 500 page and error tracking gives ValueError: Missing staticfiles manifest entry for 'images/favicon/manifest.json' which is a very bizarre and misleading error. Other actions taken: I've checked both the base.py and production.py files for any other references to DEBUG or to the DJANGO_SETTINGS variable and they are clear. I also searched other .py files that the IIS server interacts with (wsgi.py, manage.py). I have even tried setting DEBUG = False in the base.py … -
Django postgres SearchVectorField from foreign key
I'm using Django's SearchVectorField on a model and have set up a post_save signal so the search vector is updated at every save: class Product(models.Model): search_vector = SearchVectorField(null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL) @receiver(post_save, sender=Product) def create_searchvector(sender, instance, **kwargs): signals.post_save.disconnect(create_searchvector, sender=Product) instance.search_vector = SearchVector('brand') + SearchVector('name') + \ SearchVector('category__name') # i get an error here instance.save() signals.post_save.connect(create_searchvector, sender=Product) I get an error on the line I annotated above: Joined field references are not permitted in this query I'm trying to get the Category object's name property into the search vector. Anyone know how to solve this? Thanks! -
data doesn't show up while integrating django with angularJS using django rest framework
hello guys after following a tutorial on how to integrate django with angularJS when I opened the link of which the django is connected to angular through $http I get nothing over my site just a white blank screen i don't know what exactly the issue is here is my home.html where angular is connected to {% load staticfiles %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Hello</title> </head> <body ng-app=crud.demo> {% verbatim %} <div ng-controller=crud_controller> <div ng-repeat='list in data.title'> <h3> {{list.title}}</h3> <!-- <li ng-repeat ='cards in list.cards '>{{cards.title}}</li> --> <!-- <input type="text" ng-model=new_title>{{new_title}} --> <!-- <button type="button" name="button" ng-click=add(list,new_title)>hey</button> --> </div> </div> {% endverbatim%} <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"> </script> <script src="{% static "crud/crud.js" %}"></script> </body> </html> and here is my crud.js file (function(){ 'use_strict'; angular.module('crud.demo',[]).controller('crud_controller',['$scope','$http',crud_controller]); function crud_controller($scope,$http){ // $scope.add= function(list,title){ // var card={ // title:title // }; // list.cards.push(card) $scope.data=[]; $http.get('api/hello').then(function(response){ $scope.data=response.data; }); } } ()); url 'api/hello' is the link of serialized data in json format HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "title": "hello", "description": "hello", "published": true }, { "title": "hey there", "description": "cool", "published": true }, { "title": "wassup", "description": "nice", "published": false }, { "title": "ok", "description": … -
Django Rest Multiple Models
I'm trying to return a Json with Django Rest Multiple Models My Serializer.py: class ActivacionSerializer(serializers.ModelSerializer): class Meta: model = Activacion fields = ['fecha_actividad','cantidad'] class CuotaSerializer(serializers.ModelSerializer): class Meta: model = Cuota fields = ['fecha_cuota','cuota_activaciones_total'] My Views.py class ActivacionCuotaAPIView(FlatMultipleModelAPIView): querylist = [ {'queryset': Activacion.objects.filter(fecha_actividad='2018-05-01').values('fecha_actividad').annotate(cantidad=Sum('cantidad')), 'serializer_class':ActivacionSerializer}, {'queryset': Cuota.objects.filter(fecha_cuota=('2018-04-01')).values('fecha_cuota').annotate(cuota_activaciones_total=Sum('cuota_activaciones_total')), 'serializer_class':CuotaSerializer} ] The resulting Json is: [{"fecha_actividad":"2018-05-01","cantidad":597.0,"type":"Activacion"},{"fecha_cuota":"2018-04-01","cuota_activaciones_total":"605.632645","type":"Cuota"}] But I dont know how to return a Json like [{"fecha_actividad":"2018-05-01","cantidad":597.0,"type":"Activacion","fecha_cuota":"2018-04-01","cuota_activaciones_total":"605.632645","type":"Cuota"}] I mean, one day one dict is this possible? By the way this is for make charts with Amcharts -
access django app through mobile browser
I've made a project to Django, everything is fine and I use the PC local IP that Ipconfig (I'm a windows user) shows me to run server (192.168.1.4:5000). I can access the project through other laptop connected to the same wireless but can't access it through my phone browser, I've disabled firewall and also no VPN is connected in my phone. I've no idea what's wrong. -
Django not collecting static files to S3 bucket but local directory, what's wrong with the config?
So I have my settings.py set up as so: STATIC_ROOT = os.path.join(BASE_DIR, 'my_dir/static/') STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.DefaultStorageFinder', ] AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' While I have looked for problems, nothing looks out of the blue. Though running collectstatic still does it locally rather than uploading it to my S3 bucket. Is there a particular configuration I'm missing, or just something in general? I have the boto3 and storages installed. Django 2.0.3 Thanks. -
run is False in django code for .join
my code in django is : output = ',\n'.join([p.slug for p in list_posts]) run is True but don't run ',\n' enter image description here -
What does the addition of static(...) to the list do?
urlpatterns = [path('admin/', admin.site.urls),] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) Please explain what is happening here in python. Specifically, how can we add something to the urlpatterns list? Why can't we just make another path within the list and link that to an image instead of using the static(...) function? I'm new to Django and this is confusing me. -
Renaming 2 uploaded files automatically
I'm using Django framework and I'm new at it. Currently I'm working at renaming 2 uploaded files but I couldnt figure it out. Here is the code in view.py def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'core/simple_upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'core/simple_upload.html') currently, it uploads and store it in media just fine, but i need to hardcoded the 1st uploaded file into 'file1' and the 2nd uploaded file into 'file2' any help is appreciated thanks -
TypeError at /accounts/register/ 'radio' is an invalid keyword argument for this function "unable to store radio button value with django"
error TypeError at /accounts/register/ 'radio' is an invalid keyword argument for this function forms.py class CustomUserCreationForm(forms.Form): username = forms.CharField(label='Enter Username', min_length=4, max_length=150) email = forms.EmailField(label='Enter email') password1 = forms.CharField(label='Enter password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) radio = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) views.py def register(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() return redirect(reverse('accounts:login')) else: form = CustomUserCreationForm() args = {'form':form} return render(request, 'accounts/reg_form.html',args) -
Displaying Django model entries for logged in user in a profile page
I have two models. One is 'Task' and the other one is 'Entry' and I am able to see an overview of the all entries made for each task in Django Admin panel. I would like to create a similar page for logged in user to display which entries he created in db. I tried to get them by using log data with LogEntry class, but I stucked at it. Does somebody know an efficient way to do it? -
Graphql Django best way to get nested object property
Instead of doing the query like this query { allObjectC { id # self ID() nestedB_set { id nestedA_set { id # ID() we want to get } } } } We change the model like this // Models.py class ObjectA(models.Model): ... class ObjectB(models.Model): propertyB = models.ForeignKey(ObjectA, on_delete=models.CASCADE, related_name='nestedB') class ObjectC(models.Model): propertyC = models.ForeignKey(ObjectB, on_delete=models.CASCADE, related_name='nestedC') @property # new property created def nestedB_nestedA_id(self): return self.propertyC.nested_objectB.nested_objectA.id We change the graphql schema like this // schema.py class ObjectCNode(DjangoObjectType): nestedB_nestedA_id = graphene.Int(source='nestedB_nestedA_id') # as proxy nestedA_id = graphene.ID() # globalID of ObjectANode we want to get def resolve_nestedB_nestedA_id(self, info, **kwargs): return self.nestedB_nestedA_id def resolve_nestedA_id(self, info, **kwargs): return relay.Node.to_global_id(ObjectANode._meta.name, self.nestedB_nestedA_id) New Graphql Query query { allObjectC { id # self ID() nestedA_id # nested nested ID() we want to get } } Any best pratice or ideas for this ? Thanks in advance . -
Vue warn: property or method 'processLogout' is not defined on the instance but defined during render
I'm having an issue with Vue. At this point I've read things like this detailing this error occurring when you try to define a method on the root instance, then reference it in local scope. My issue is slightly different because it is defined in local scope, so I'm not sure what to make of this error. I've also looked at this, and this. Here is my App.vue: <template> <div id="app"> <router-link to="/Home">home</router-link> <router-link to="/Login">login</router-link> <router-view/> </div> </template> <script> export default { name: 'App' } console.log('app.vue loading') </script> My main.js: // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import store from './store' import router from './router' import Home from './components/Home' import Login from './components/Login' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { App, Home, Login }, template: '<App/>' }) console.log('main js loading'); The component the issue is coming from: <template> <div class="login"> <head> <title>{{title}}</title> </head> <form for="login" id="loginMain"> <label for="username">Username:</label> <input type="text" id="username"></input> <label for="password">Password:</label> <input type="password"></input><br/><br/> <button for="login" @click="processLogin">LOGIN</button> <button for="logout" @click="processLogout">LOGOUT</button> </form> <p> Your login status: {{ loginStatus … -
Celery tasks not executed in Django app deployed on Heroku
I've deployed my working django application on heroku. The whole application along with the celery tasks is working in local environment. But when I deploy it in heroku the tasks are not being run. When I manually open heroku python manage.py shell and start the task from there, its running. The task is actually supposed to run when I click a button on a page. There it's not working. Files for reference: myapp/celery.py from __future__ import absolute_import, unicode_literals from celery import Celery import os from vms.settings import USE_ELASTIC_SEARCH os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'vms.settings') app = Celery('vms', broker=os.environ.get('REDIS_URL','redis://localhost'), include=['cve.tasks','cpe.tasks']) app.conf.update( result_backend='django-db', result_expires=86400*2, timezone = 'Asia/Kolkata' ) if __name__ == '__main__': app.start() Procfile web: gunicorn vms.wsgi worker: celery -A vms worker -l info -
Custom (swappable) models for Django OAuth Toolkit
I need to create custom Django OAuth Toolkit models. I have an app with these models: from django.utils.translation import ugettext_lazy as _ from oauth2_provider.models import ( AbstractApplication, AbstractGrant, AbstractAccessToken, AbstractRefreshToken ) class Application(AbstractApplication): GRANT_TYPES = ( (AbstractApplication.GRANT_AUTHORIZATION_CODE, _("Authorization code")), (AbstractApplication.GRANT_IMPLICIT, _("Implicit")), ) class Grant(AbstractGrant): pass class AccessToken(AbstractAccessToken): pass class RefreshToken(AbstractRefreshToken): pass And settings: INSTALLED_APPS = [ ... 'oauth2_provider', ... 'apps.oauth.apps.OauthConfig', ... ] OAUTH2_PROVIDER_GRANT_MODEL = 'oauth.Grant' OAUTH2_PROVIDER_APPLICATION_MODEL = 'oauth.Application' OAUTH2_PROVIDER_ACCESS_TOKEN_MODEL = 'oauth.AccessToken' OAUTH2_PROVIDER_REFRESH_TOKEN_MODEL = 'oauth.RefreshToken' And when i trying to make migrations, i got this error: ValueError: The field oauth2_provider.AccessToken.application was declared with a lazy reference to 'oauth.application', but app 'oauth' isn't installed. The field oauth2_provider.AccessToken.source_refresh_token was declared with a lazy reference to 'oauth.refreshtoken', but app 'oauth' isn't installed. The field oauth2_provider.Grant.application was declared with a lazy reference to 'oauth.application', but app 'oauth' isn't installed. The field oauth2_provider.RefreshToken.access_token was declared with a lazy reference to 'oauth.accesstoken', but app 'oauth' isn't installed. The field oauth2_provider.RefreshToken.application was declared with a lazy reference to 'oauth.application', but app 'oauth' isn't installed. If i remove OAUTH2_PROVIDER_***_MODEL settings and run makemigrations again, i got many fields.E304 and fields.E305 errors: SystemCheckError: System check identified some issues: ERRORS: oauth.AccessToken.application: (fields.E304) Reverse accessor for 'AccessToken.application' clashes with reverse accessor for … -
use rest framework APIView to post item to cart
I have a use case of adding the items in a cart. In rest framework documentation, i saw an APIView where request.data is sent in the serialzer and checked if it is valid or not, if valid then return success response otherwise error. But without doing calculation like if item is present in the session or not how it gonna store the item to the cart table. I drew the logic(which I am totally unsure but has tried) but i could not align it in a rest framework way(APIView). Here is what I tried. class CartAPI(APIView): serializer_class = serializers.CartSerializer def get(self, request, format=None): reply = {} try: carts = Cart.objects.all() reply['data'] = self.serializer_class(carts, many=True).data except Cart.DoesNotExist: reply['data'] = [] return Response(reply, status.HTTP_200_OK) def post(self, request, format=None): reply = {} cart = Cart(request) product_id = request.data.get('product', None) quantity = request.data.get('quantity', None) try: product = Variation.objects.get(id=product_id) except Variation.DoesNotExist: pass isProductInCart = False for cart_item in cart: if cart_item.item.id == product.id: cart_item.quantity = quantity isProductInCart = True if not isProductInCart: # create and save new item in the cart cart_product = CartItem.objects.create(cart=cart) cart_product.item = product cart_product.quantity = quantity cart_product.save() reply['data'] = self.serializer_class(cart_product, data=request.data) return Response(reply, status.HTTP_200_OK) class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, …