Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to save data in Database using for loop
my proposal: I want add network IP range with prefix in web UI and need to process using command ipaddress.IPv4Network(subnet).hosts()) then after IP range will crate and save all range of IP into DATABASE. I have tried deferent methods still not able to complete my requirement. some one could help about. below the code which I made. def Indexping(request): form = IpModelForm Ipform = {'form':form} if request.method=='POST': subnet = IpModelForm(request.POST) if subnet.is_valid: data= list(ipaddress.IPv4Network(subnet).hosts()) for f in data: #f = [x for x in subnet] f.save() Exception Value: Only one '/' permitted in Getting Below Error: AddressValueError at /cbv/ind/ Only one '/' permitted in Request Method: POST Request URL: http://127.0.0.1:8000/cbv/ind/ Django Version: 4.0.2 Exception Type: AddressValueError Exception Value: Only one '/' permitted in Exception Location: D:\Program Files\Python\Python39\lib\ipaddress.py, line 162, in _split_optional_netmask Python Executable: E:\Django_Projects\Portal-env\Scripts\python.exe Python Version: 3.9.10 Python Path: ['E:\Django_Projects\Portal-env\portal', 'D:\Program Files\Python\Python39\python39.zip', 'D:\Program Files\Python\Python39\DLLs', 'D:\Program Files\Python\Python39\lib', 'D:\Program Files\Python\Python39', 'E:\Django_Projects\Portal-env', 'E:\Django_Projects\Portal-env\lib\site-packages'] Server time: Sat, 19 Feb 2022 09:35:57 +0000 -
Getting SUM for each unique fields in Django Query
I have the following table relations. I want SUM of total_cost from Sales_Transaction for each party_name from the Party table. The Parties have 1:M relation with Sales and Sales has 1:M relation with Sales_Transction. I tried this query but it returns the sum for all parties: Party.objects.aggregate(sales=Sum('sales__salestransaction__total_cost')) This is similar to this simple query: SalesTransaction.objects.aggregate(sales=Sum('total_cost')) I want output like this: | Party Name | Total Purchase | ----------------------------- |Party 1 | total_cost (calculated form Sales Transaction) |Party 2 | total_cost (calculated form Sales Transaction) How can I achieve these results in Django Query? -
admin change_view is being called twice
Is there a chance to keep django admin from calling change_view twice when clicking "save and continue editing"? class SomeAdmin(admin.ModelAdmin): form = SomeAdminForm def change_view(self, request, object_id, form_url = "", extra_context = None): extra_context = extra_context or {} print("test") return super().change_view(request, object_id, form_url, extra_context = extra_context,) prints test once, when entering the change form layout, prints test twice when clicking "save and continue editing". I run a costly query inside that change_view function, that needs to be displayed in the admin change form. But I want it to only run once. Any ideas? -
AttributeError: module 'BackendApp.views.GoogleLogin' has no attribute 'as_view'
path('dj-rest-auth/google/', GoogleLogin.as_view(), name='google_login'), AttributeError: module 'BackendApp.views.GoogleLogin' has no attribute 'as_view' I have this error coming from url.py which is weird as I am following this guide https://dj-rest-auth.readthedocs.io/en/latest/installation.html on the Google section. I am pretty sure I have all the relevant settings and I copied the codes for url.py and GoogleLogin.py. Does anyone have any clues on how to deal with this issue? url.py from django.contrib import admin from django.urls import path from django.urls import include, re_path from django.conf.urls.static import static from django.conf import settings from dj_rest_auth.views import PasswordResetConfirmView, PasswordResetView from django.views.generic import TemplateView from .router import router from BackendApp.views import P2PListingModule, empty_view, GoogleLogin urlpatterns = [ path('admin/', admin.site.urls), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('entity/', include(router.urls)), path('enduser/<str:pk>/service/', P2PListingModule.userServiceListing), path('enduser/<str:pk>/request/', P2PListingModule.userRequestListing), path('enduser/<str:pk>/swap/', P2PListingModule.userSwapListing), path('enduser/<str:pk>/premade', P2PListingModule.userPremadeListing), path('entity/p2p_listing/order/', P2PListingModule.placeOrder), path('api/p2plisting/service', P2PListingModule.ServiceListingView.as_view()), path('api/p2plisting/request', P2PListingModule.RequestListingView.as_view()), path('api/p2plisting/swap', P2PListingModule.SwapListingView.as_view()), path('api/p2plisting/premade', P2PListingModule.PremadeListingView.as_view()), re_path(r'^', include('django.contrib.auth.urls')), path('dj-rest-auth/password/reset/', PasswordResetView.as_view(), name="rest_password_reset"), path( "dj-rest-auth/password/reset/confirm/", PasswordResetConfirmView.as_view(), name="rest_password_reset_confirm", ), # path( # "/dj-rest-auth/password/reset/confirm/<uidb64>/<token>/", # PasswordResetConfirmView.as_view(), # ) path('dj-rest-auth/google/', GoogleLogin.as_view(), name='google_login'), path('accounts/', include('allauth.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # urlpatterns = [ # url(r'^admin/', include(admin.site.urls)), # ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) BackendApp.views.GoogleLogin.py from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from allauth.socialaccount.providers.oauth2.client import OAuth2Client from dj_rest_auth.registration.views import SocialLoginView class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter #I do not know if this client id is the callback_url … -
Reverse for 'chi_tiet_hop_dong' with keyword arguments '{'so_hd': ''}' not found. 1 pattern(s) tried: ['chi_tiet_hop_dong/(?P<so_hd>[^/]+)/$']
I have the issue this error my model. class testimport(models.Model): id=models.AutoField(primary_key=True) so_hd=models.CharField( max_length=50, unique=True) ten_kh=models.CharField( max_length=500) def get_absolute_url(self): return "/chi_tiet_hop_dong/%s/" % self.so_hd class report(models.Model): id=models.AutoField(primary_key=True) so_hd=models.ForeignKey(testimport, on_delete=models.CASCADE, to_field="so_hd") If I dont use to_field="so_hd" in model report, the error doesnt appear, but I need to link it with "so_hd" in model testimport not "id primary key" in model testimport without using to_field my view: def chi_tiet_hop_dong(request,so_hd): contract=testimport.objects.filter(so_hd=so_hd) print("số hợp đồng trong def chi tiết hợp đồng",so_hd) request.session["save_so_hd"]=json.loads(json.dumps(so_hd)) lst_contract=request.session["get_contract_detail"] try: the_next = lst_contract[lst_contract.index(so_hd) + 1] print("the next",the_next) except: the_next=None try: the_prev=lst_contract[lst_contract.index(so_hd) - 1] print("the prev",the_prev) except: the_prev=None baocao=report.objects.filter(so_hd=so_hd) form=AddReportForm() return render(request, "caller_template/contract_detail.html", {"contract":contract,"the_next":the_next,"the_prev":the_prev,"baocao":baocao,"form":form}) I check to print out the_next, the_prev and so_hd, it is ok my url: path('chi_tiet_hop_dong/<str:so_hd>/', CallerViews.chi_tiet_hop_dong, name="chi_tiet_hop_dong"), Please help me -
Is there any Pythonic way to manipulate Dictionaries to follow DRY philosophy in Django?
I have got dictionary set of required queries as shown below: [{'primary_attribute__name': 'Color', 'primary_attr_values__name': 'Red'}, {'primary_attribute__name': 'Color', 'primary_attr_values__name': 'Green'}] Now I want : [{'primary_attribute__name: 'Color', { 'primary_attr_values__name': 'Red', 'primary_attr_values__name': 'Green', 'primary_attr_values__name': 'Yellow' }] Or is this good approach: primary_attribute= { "Color" : {"primary_attr_values__name" : ["red", "green", "yellow"]} } How it can be achieved? -
How to configure redis 6 in django
I know how to configure postgress on digitalocean with django. However I have a redis 6 database cluster and I've been unable to configure it with my django app. Here is the postgress configuration as is in settings.py POSTGRES_DB = os.environ.get("POSTGRES_DB") #database name POSTGRES_PASSWORD = os.environ.get("POSTGRES_PASSWORD") # database user password POSTGRES_USER = os.environ.get("POSTGRES_USER") # database username POSTGRES_HOST = os.environ.get("POSTGRES_HOST") # database host POSTGRES_PORT = os.environ.get("POSTGRES_PORT") # database port POSTGRES_READY = ( POSTGRES_DB is not None and POSTGRES_PASSWORD is not None and POSTGRES_USER is not None and POSTGRES_HOST is not None and POSTGRES_PORT is not None ) if POSTGRES_READY: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": POSTGRES_DB, "USER": POSTGRES_USER, "PASSWORD": POSTGRES_PASSWORD, "HOST": POSTGRES_HOST, "PORT": POSTGRES_PORT, } } The environment variables in DO are below. POSTGRES_HOST ${db.HOSTNAME} POSTGRES_DB ${db.DATABASE} POSTGRES_USER ${db.USERNAME} POSTGRES_PASSWORD ${db.PASSWORD} POSTGRES_PORT ${db.PORT} My redis 6 details are username = default password = ... host = llr-redis-db-do-user-47-0.b.db.ondigitalocean.com port = 25061 How would I have this configured with the environment variables in DO then pass to the settings.py?? -
"response": "strptime() argument 1 must be str, not datetime.datetime" django datetime format problem
In Django, I have written a delete method in which I am getting some requests of data from the delete API The requested data is [ { "acerage": 1, "batch_health": null, "actual_produce": null, "actual_yield_per_acre": null, "batch_id": 2583, "batch_status": "running", "commodity_id": 6, "commodity_variety_id": 20, "current_gdd": null, "current_pdd": null, "expected_delivery_date": "2022-02-15T18:30:00.000Z", "expected_produce": null, "farm_id": "1806", "historic_gdd": null, "historic_pdd": null, "historical_yield_per_acre": null, "sop_adherence": null, "stage": "germination", "start_date": "2022-02-06T18:30:00.000Z" } ] I am deleting a row in my DB based on batch_id by using the delete method and the delete method looks like def destroy(self, request, *args, **kwargs): """ This function is used to destroy batch object """ try: instance = self.get_object() instance.batch_status = 'aborted' instance.save() solr_delta_import() except Exception as e: return Response({"response": str(e)}, status=status.HTTP_400_BAD_REQUEST) return Response({"response": "deleted successfully"}, status=status.HTTP_200_OK) and the row gets deleted when we run this function My problem here is the requested data values start_time and expected_delivery_date is coming in the string format but due to some calculations in my model file, I am converting that string to a DateTime format which looks like this the model file looks like def update_batch_median_health(self): if self.start_date and self.expected_delivery_date: if self.id: start_date = datetime.strptime(self.start_date, '%Y-%m-%dT%H:%M:%SZ') expected_delivery_date = datetime.strptime(self.expected_delivery_date, '%Y-%m-%dT%H:%M:%SZ') else: start_date = datetime.combine(self.start_date, … -
keep getting error: ModuleNotFoundError: No module named 'requests' when i have requests installed
i have python installed but i keep seeing the below error when i try to import requests. File "/x/y/z/views.py", line 3, in <module> import requests ModuleNotFoundError: No module named 'requests' here is what my code looks like: from django.shortcuts import render from django.http import HttpResponse import requests def say_hello(request): return render(requests, 'hello.html') apologies in advance if this is a dumb question, i have just started to learn django. -
Create Single Forms by Two Models in Django with Dynamic Fields
I want to create Django Forms to save transactions for the store. I want a final template similar to this. The ER Diagram for my database is also shown in the image. My Django Models are: class Party(models.Model): party_id = models.BigAutoField(primary_key=True) party_name = models.CharField(max_length=128) party_phone = models.CharField(max_length=128) party_address = models.CharField(max_length=128) def __str__(self): return self.party_name class Items(models.Model): item_no = models.BigAutoField(primary_key=True) item_type = models.BooleanField(default=True) item_name = models.CharField(max_length=128) item_qty = models.PositiveIntegerField(default=0) item_cost = models.PositiveIntegerField(default=0) def __str__(self): return self.item_name class Sales(models.Model): invoice_no = models.BigAutoField(primary_key=True) invoice_date = models.DateField(default=date.today) party = models.ForeignKey(Party, on_delete=models.CASCADE) def __str__(self): return str(self.invoice_no) class SalesTransaction(models.Model): sales = models.ForeignKey(Sales, on_delete=models.CASCADE) items = models.ForeignKey(Items, on_delete=models.CASCADE) purchase_qty = models.PositiveIntegerField(default=0) total_cost = models.PositiveIntegerField(default=0) def __str__(self): return self.item_name I can achieve this with AJAX but I don't think it is the best solution because lots of validations have to be made with hardcoding. How can I create Django Form to save data in that multiple tables in a single Save Click? -
The login function in Django not working properly
views.py def login_view(request): form = AuthenticationForm() if request.method == 'POST': form = AuthenticationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request,user) messages.info(request,'登入成功!') return redirect('index') else: messages.error(request,'帳戶無效或密碼錯誤! 請重試!') else: messages.error(request,'帳戶無效或密碼錯誤! 請重試!') context = {'form':form} return render(request,'customer/login.html',context) login.html <form method="POST" action="" style="position:absolute;top:300px;left:125px;"> {% csrf_token %} {{ form.username|as_crispy_field }}<br> {{ form.password|as_crispy_field }}<br> <button class="btn btn-primary" type="submit">登入</button> </form> For the login function in Django, I am trying to use the username and password based on the User model in django.contrib.auth.models to login into the account. However, even though I am using my superuser status to login and the error message appears showing that invalid username or password. May I ask is AuthenticationForm following the User model information to authenticate the user or anything I am missing? -
The Django admin site
I start the development server and explore it. When I open the Web browser and go to “/admin/” on my local domain, http://127.0.0.1:8000/admin/.I face this screen: enter image description here -
Django: Query .all() not hitting the database
THe django docs says: Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result. After calling all() on either object, you’ll definitely have a QuerySet to work with. When a QuerySet is evaluated, it typically caches its results. If the data in the database might have changed since a QuerySet was evaluated, you can get updated results for the same query by calling all() on a previously evaluated QuerySet. I am using Django-Debug-Toolbar to optimize a query. If I have code like this (returning an empty list to ensure .all() is hitting the DB at this point in time: def get_querysets(): foo_list = Foo.objects.filter(...).all() bar_list = Bar.objects.filter(...).all() caz_list = Caz.objects.filter(...).all() return [] then Django debug toolbar won't register those queries, i.e. DB was not querried. However if I change it to: def get_querysets(): foo_list = Foo.objects.filter(...).all() bar_list = Bar.objects.filter(...).all() caz_list = Caz.objects.filter(...).all() print(foo_list) print(bar_list) print(caz_list) return [] Now in the toolbar I can see the queries. I know querysets are lazy, but the whole point of .all() is to make it hit the … -
Not viewing file in flutter
I have converted my Django website into flutter app. in that website, view file link is there. but in APK file, it is not viewing when I click on it. How to solve this problem. Please tell. -
created virtual environment , but cant access it
it shows created virtual environment. But it is not redirect to virtual environment . after I upgraded the pip no changes where appear . please help me to get that. enter image description here -
Django regex not working when adding other branches to url
I am a complete beginner in Django, and I have encountered a problem while trying to set up a url for each "room". Here is the code: from django.conf.urls import url from . import views urlpatterns = [ url(r'^home/$', views.home, name='home'), url(r'^room/<str:pk>/$', views.room, name='room'), ] Everything was working perfectly, until I add /<str:pk>/$. I have also add this code in the views.py section: def room(request,pk): return render(request, 'base/room.html') However I still get an error when loading the website. Image of the error message Does someone know how to make it work? -
ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser
I'm trying to use Django REST Framework with ModelSerializer to handle user authentication, but I haven't found an elegant way to add the user to my entry. Here is my models class Entry(models.Model): slug = models.SlugField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=200) description = models.TextField() publish = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) these are the serializers used to create the user and entry class EntrySerializer(serializers.ModelSerializer): class Meta: model = Entry fields = ['slug', 'author', 'created', 'modified', 'title', 'description'] read_only_fields = ['code', 'author', 'slug', 'created', 'modified'] def create(self, validated_data): if self.request.user.is_authenticated: validated_data['author'] = self.request.user return super().create(validated_data) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password'] extra_kwargs = {'password':{ 'write_only':True, 'required':True }} def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) return user these are the ModelViewSets to render the models into views class PostUserWritePermission(BasePermission): def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True return obj.author == request.user class EntryViewSet(viewsets.ModelViewSet, PostUserWritePermission): queryset = Entry.objects.all() serializer_class = EntrySerializer lookup_field = 'slug' permission_classes = [PostUserWritePermission] authentication_classes = (TokenAuthentication,) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer -
What happens to other attributes after Django queryset distinct is used?
On this query set what will happen to the score attribute if I do something like: myqset.distinct('Name')? Does it just take one of the score values or is there something I can do to get the average of the scores? Name Score John 100 John 90 Adam 80 Adam 70 -
ProgrammingError at /products/ or 500 error when i click to another app in Heroku but it works locally
My project works locally but i get 500 errors on heroku when trying to press a link to another app which was products in my project. I gProgrammingError at /products/ relation "products_product" does not exist LINE 1: ...uct"."image_url", "products_product"."image" FROM "products_... "2022-02-19T01:51:05.415919+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/loader_tags.py", line 150, in render 2022-02-19T01:51:05.415919+00:00 app[web.1]: return compiled_parent._render(context) 2022-02-19T01:51:05.415920+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/base.py", line 162, in _render 2022-02-19T01:51:05.415920+00:00 app[web.1]: return self.nodelist.render(context) 2022-02-19T01:51:05.415920+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/base.py", line 938, in render 2022-02-19T01:51:05.415921+00:00 app[web.1]: bit = node.render_annotated(context) 2022-02-19T01:51:05.415921+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/base.py", line 905, in render_annotated 2022-02-19T01:51:05.415922+00:00 app[web.1]: return self.render(context) 2022-02-19T01:51:05.415922+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/loader_tags.py", line 62, in render 2022-02-19T01:51:05.415923+00:00 app[web.1]: result = block.nodelist.render(context) 2022-02-19T01:51:05.415923+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/base.py", line 938, in render 2022-02-19T01:51:05.415923+00:00 app[web.1]: bit = node.render_annotated(context) 2022-02-19T01:51:05.415924+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/base.py", line 905, in render_annotated 2022-02-19T01:51:05.415924+00:00 app[web.1]: return self.render(context) 2022-02-19T01:51:05.415924+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/base.py", line 988, in render 2022-02-19T01:51:05.415924+00:00 app[web.1]: output = self.filter_expression.resolve(context) 2022-02-19T01:51:05.415924+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/base.py", line 698, in resolve 2022-02-19T01:51:05.415925+00:00 app[web.1]: new_obj = func(obj, *arg_vals) 2022-02-19T01:51:05.415925+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/defaultfilters.py", line 550, in length 2022-02-19T01:51:05.415925+00:00 app[web.1]: return len(value) 2022-02-19T01:51:05.415925+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/db/models/query.py", line 269, in len 2022-02-19T01:51:05.415926+00:00 app[web.1]: self._fetch_all() 2022-02-19T01:51:05.415926+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/db/models/query.py", line 1303, in _fetch_all 2022-02-19T01:51:05.415926+00:00 app[web.1]: … -
Django database deployment issue regarding database
When I run app server locally through "python manage.py runserver" I am able to register users into my postgresql database but when I open my website with the url it is hosted with, it doesn't do anything when I submit the register. It just returns me to the home page with no new user in the database. Any obvious reasons for such behavior? -
Django forms: object has no attribute cleaned data
I'm fairly new to Django. I have been getting this error when I try to use form.cleaned_data. Everywhere I've checked online says that this is because you might not be using the is_valid function which I am. My objective is to create a set of records which stores the student ID and the subject ID as foreign keys in a model called Sub_and_stu. I'm open to any other (as simple?) ways of achieveing this. views.py @csrf_protect def select_subs(request): form1 = Sub_selection1(request.POST) form2 = Sub_selection2(request.POST) form3 = Sub_selection3(request.POST) form4 = Sub_selection4(request.POST) user = request.user if form1.is_valid and form2.is_valid and form3.is_valid and form4.is_valid: data1 = form1.cleaned_data sub1=data1['subject_id'] Sub_and_stu.objects.create(student_id=user,subject_id=sub1) data2 = form2.cleaned_data sub2=data2['subject_id'] Sub_and_stu.objects.create(student_id=user,subject_id=sub2) data3 = form3.cleaned_data sub3=data3['subject_id'] Sub_and_stu.objects.create(student_id=user,subject_id=sub3) data4 = form4.cleaned_data sub4=data4['subject_id'] Sub_and_stu.objects.create(student_id=user,subject_id=sub4) context={'form1':form1,'form2':form2,'form3':form3,'form4':form4} return render(request,'select_subs.html',context) models.py class Subject(models.Model): subject_id=AutoSlugField(unique=True) name = models.CharField(max_length=50) def __str__(self): return self.name class Sub_and_stu(models.Model): record_id=AutoSlugField(unique=True) student_id=models.ForeignKey(User,on_delete=models.CASCADE) subject_id=models.ForeignKey(Subject,on_delete=models.CASCADE) class Sub_and_teachers(models.Model): record_id=AutoSlugField(unique=True) teacher_id=models.ForeignKey(User,on_delete=models.CASCADE) subject_id=models.ForeignKey(Subject,on_delete=models.CASCADE) forms.py class Sub_selection1(ModelForm): class Meta: model = Sub_and_stu fields=['subject_id'] #Other subject selection forms are basically a copy of this. I need the user to pick multiple subejcts at the same time snippet from select_subs.html <form> {%csrf_token%} <h3>Subject 1</h3> {% render_field form1.subject_id class='pure-input-1 pure-input-rounded' } <h3>Subject 2</h3> {% render_field form2.subject_id class='pure-input-1 pure-input-rounded' } <h3>Subject 3</h3> {% … -
How to Nest URL routes in Django Rest Framework (DRF) RetrieveUpdateDestroyAPIView without router
I am using the Django rest framework and RetrieveUpdateDestroyAPIView and trying to Implement nested URL patterns. # my current URLs structure is like /api/v1/kitchens/ - ListCreateAPIView /api/v1/kitchens/1/ - RetrieveUpdateDestroyAPIView /api/v1/orders/ - ListCreateAPIView /api/v1/orders/1/ - RetrieveUpdateDestroyAPIView /api/v1/items/ - ListCreateAPIView /api/v1/items/1/ - RetrieveUpdateDestroyAPIView The above structure works fine with all the operations but to get the list of items or orders under a single kitchen I am trying to achieve something live below. the views.py has something like below. class KitchenListView(generics.ListCreateAPIView): queryset = Kitchen.objects.all() serializer_class = KitchenSerializer pagination_class = LimitOffsetPagination permission_classes = (permissions.IsAuthenticatedOrReadOnly,) authentication_classes = (TokenAuthentication,) filter_backends = (DjangoFilterBackend,) filter_fields = ("user",) class KitchenDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Kitchen.objects.all() serializer_class = KitchenDetailsSerializer permission_classes = ( permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, ) authentication_classes = (TokenAuthentication,) # I want to create this structure. /api/v1/kitchens/ - List /api/v1/kitchens/1/ - Details /api/v1/kitchens/1/orders/ - Orders List /api/v1/kitchens/1/orders/1/ - Order Details /api/v1/kitchens/1/items/ - Items List /api/v1/kitchens/1/items/1/ - Item Details I am trying to achieve something like this. Please suggest to me the better solution if anyone has and what would be better to go with generic API views or Viewsets as my project is a large-scale project. Thanks in Advance. -
Access to XMLHttpRequest at 'http://localhost:8000/api/auth/jwt/create/' from origin 'http://localhost:63342' has been blocked by CORS policy:
I am trying to connect django and Vue API to login. I am using JWT with simple jwt and djoser library, and I have already created user. As you can see the postman, it works fine. Does anyone know how to fix this error?? However, I cannot connect from index.html (ajax) This is the ajax. .... var app = new Vue({ el: '#app', data: { email: '', password: '' }, mounted: function() {}, methods: { login(){ if (this.email == ''||this.password == '') { alert("Email or password cannot be empty"); location. reload(); } var data_l = {}; data_l.email = this.email; data_l.password = this.password; var formData = JSON.stringify(data_l); console.log(formData); $.ajax({ url: "http://localhost:8000/api/auth/jwt/create/", type: "post", dataType: "json", data: formData, contentType: "application/json", success: function(rs) { console.log(rs); if (rs.code == "0") { console.log(rs); alert("Login successful!"); window.location.href = ""; } else { alert(rs.msg); } }, error: function() {} }); }, jump_to_signup() { window.location.href = "signup.html"; }, jump_to_Fpwd(){ window.location.href = "forgotpassword.html"; } } }) </script> </body> </html> This is settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'djoser', 'fitness_app', 'user', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'fitness.urls' CORS_ORIGIN_ALLOW_ALL = True -
django-celery-beat loading task but not executing?
I have an application structured as follows. - api -api settings.py celery.py -core tasks.py -scripts cgm.py On running the following command I can see my task get loaded into the database however it does not actually run and I'm trying to understand why. celery -A api beat -l debug -S django_celery_beat.schedulers.DatabaseScheduler Here is my code. settings.py (relevant parts) INSTALLED_APPS = ( ..., 'django_celery_beat', ) CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') app = Celery('api') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() tasks.py from django_celery_beat.models import PeriodicTask, IntervalSchedule schedule, created = IntervalSchedule.objects.get_or_create( every=10, period=IntervalSchedule.SECONDS, ) PeriodicTask.objects.get_or_create( interval=schedule, name='Import Dexcom Data', task='core.scripts.cgm.load_dexcom', ) cgm.py from monitor.models import GlucoseMonitor def load_dexcom(): from core.models import User user = User.objects.get(username='xxx') from pydexcom import Dexcom dexcom = Dexcom("xxx", "xxx", ous=True) # add ous=True if outside of US bg = dexcom.get_current_glucose_reading() data = GlucoseMonitor.objects.create( user = user, source = 1, blood_glucose = bg.mmol_l, trend = bg.trend, created = bg.time ) data.save() I can run the load_dexcom() manually and it works. My guess is I'm not dot-walking the task properly and it's not finding it but it's not showing any errors in the code. When I run the celery command I can see it load the record … -
Distinct not working in DRF sqlite database
Distinct not working.I am using sqlite in backend class getPatient(generics.ListAPIView): def list(self, request): queryset = Patient.objects.distinct() serializer = PatientSerializer(queryset, many=True) return Response({'patient': serializer.data})