Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a second List in the Admin class , Django
'class BookingAdmin(admin.ModelAdmin): list_diplay=('id','title', 'roomsize', 'hostel', 'features','price','status' list_editable=('status',) the above code doesnt run, however without the second list(list_editable) as shwon below the code runs perfectly 'class BookingAdmin(admin.ModelAdmin): list_diplay=('id','title', 'roomsize', 'hostel', 'features','price','status')' the error <class 'main.admin.BookingAdmin'>: (admin.E121) The value of 'list_editable[0]' refers to 'status', which is not a field of 'main.Booking'. -
How to increase quantity of item in cart in Django?
My add-to-cart views. Hello everyone, I'm completely new to Django and I tried to create a simple eCommerce web application. I tried to create a logic that increases the item that is available in the cart, but I don't why the item in the cart is not working. Maybe there is an error in logic can someone help. def add_cart(request, product_id): current_user = request.user #Getting the product id product = Product.objects.get(id=product_id) #User is authenticated or not if current_user.is_authenticated: if request.method == 'POST': for item in request.POST: key = item value = request.POST[key] is_cart_item_exists = CartItem.objects.filter(product=product, user=current_user).exists() if is_cart_item_exists: cart_item = CartItem.objects.filter(product=product, user=current_user) id = [] for item in cart_item: id.append(item.id) else: cart_item = CartItem.objects.create( product = product, quantity = 1, user = current_user, ) cart_item.save() return redirect('cart') #User is not authenticated else: if request.method == 'POST': for item in request.POST: key = item value = request.POST[key] try: #Get the cart using cart id cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() is_cart_item_exists = CartItem.objects.filter(product=product, cart=cart).exists() if is_cart_item_exists: cart_item = CartItem.objects.filter(product=product, cart=cart) id = [] for item in cart_item: id.append(item.id) else: item = CartItem.objects.create(product=product, quantity=1, cart=cart) #create new cart item item.save() else: cart_item = CartItem.objects.create( product … -
Multi Level Template Inheritance using Jinja
I am working on a multilevel template inheritance using jinja. datasource.html and event1.html is rendering correctly but event2.html and event3.html are not rendering. when I click on Event 2 and Event 3 links, I am having the page of event1.html. Nothing happens when I click Event 2 and Event 3 links. Is it due to any mistake i done in inheriting or something else. Is there any way to solve this layout.html <!DOCTYPE html> <html lang="en"> <head> </head> <body> <header> </header> <section> {% block content %} {% endblock %} </body> </html> datasource.html {% extends 'layout.html' %} {% block content %} <li> <a href="#tab1">Event 1</a></li> <li> <a href="#tab2">Event 2</a></li> <li> <a href="#tab3">Event 3</a></li> <div> {% block content1 %} {% endblock %} </div> {% endblock %} event1.html {% extends 'datasource.html' %} {% block content1 %} <div> <p> this is event 1 </p> </div> {% endblock %} event2.html {% extends 'datasource.html' %} {% block content1 %} <div> <p> this is event 2 </p> </div> {% endblock %} event3.html {% extends 'datasource.html' %} {% block content1 %} <div> <p> this is event 3 </p> </div> {% endblock %} -
Reverse for 'author' with arguments '('',)' not found. 1 pattern(s) tried: ['blogapp/author/(?P<pk>[^/]+)/\\Z'
while running http://127.0.0.1:8000/blogapp/blog/ , in django 4.0, i got error reverse for... not found and this error occurs when i add (post.author.id) in href which is in template mentioned line 15 if require more information please comment below views.py def authorview(request,pk): user=User.objects.get(id=pk) return render(request,'blogapp/authorview.html',{'user':user}) In template C:\Users\SHAFQUET NAGHMI\blog\blogapp\templates\blogapp\blogretrieve.html, error at line 15 templates {% load static %} {% block content %} <h1>Blog </h1> <link rel="stylesheet" href="{% static 'blogapp/blogretrieve.css' %}"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> {% for post in q %} <div class="jumbotron jumbotron-fluid"> <div class="container"> <h2 class="display-1">{{post.title}} </h2><br> <p class="display-2">{{post.Newpost}}</p> <a href="{% url 'blogapp:author' post.author.id %}">{{post.author}}</a <!-- line 15 --> <small class="display-3">{{post.created_date}}</small> </div> </div> {% endfor %} app_name='blogapp' urlpatterns=[ path('',views.home,name='home'), path('createblog/',views.blogview,name='blogview'), path('blog/',views.blogretrieve,name='blog'), path('signup/',views.signupview,name='signup'), path('login/',views.loginview,name='login'), path('logout/',views.logoutview,name='logout'), path('author/<str:pk>/',views.authorview,name='author'), ] -
saving day wise logs in Azure App Service for Django Application
Below is the logging format I have for a DRF application in azure app service. I tried using Timed Rotating File handler but I was not able to save the logs with that option. Also, when ever the app service restarts, the previous logs are getting erased. Is there a way to maintain day wise logs in azure app service. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'filters':{ 'error_mails': { '()': 'django.utils.log.CallbackFilter', 'callback':'app.log.CustomExceptionReporter' }, 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, }, 'handlers': { 'logfile': { 'level':'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': f'{BASE_DIR}/app_log.log', 'maxBytes': 9000000, 'backupCount': 10, 'formatter': 'standard' }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'include_html' :True, 'reporter_class':'app.log.CustomExceptionReporter', # 'filters':['require_debug_false',] }, }, 'loggers': { 'django': { 'handlers':['logfile','mail_admins'], 'propagate': True, 'level':'ERROR', }, 'django.request':{ 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'app': { 'handlers': ['logfile','console'], 'level': 'INFO', 'propogate': True, } } } -
Search Django Model Returns All Instead Of Filter
I am trying to search my Django model but, cannot return the filter result. I am getting all items in the model. class singleview(generics.ListCreateAPIView): authentication_classes = [] permission_classes = [] search_field = ['name'] filter_backends= (filters.SearchFilter,) queryset = Product.objects.all() serializer_class =ProductSerializer The Url is: url(r'^api/dualsearch/$', views.singleview.as_view()), When searching: http://localhost:8000/api/dualsearch/?name=n I return all items. Could you please help return the results in the filter? -
How to get a Model variable name from another model in django
I have two models in django model Model.py class RequestTemplate(models.Model): name = models.CharField(max_length=50) Author=models.CharField(max_length=50) defaultvalues=models.CharField(max_length=50) class Request(models.Model): name = ?? # Author = ?? starttime = models.DateTimeField(default=timezone.now) endtime = models.DateTimeField(default=None) so the idea is that i want to create Requesttemplate which i can use in the future to create a Request object that will take the name and the Author variables from the template. I tried to use Forgienkey to the name variable, but in case i updated the template in the future i dont want to get my Request updated. Conclusion: I want to connect the Request with the template for one time (to get the variables names) and then keep it independent from the template. Any ideas? -
gunicorn shows connection error [Errno 111]
Hi im building a Django app with docker, gunicorn and nginx and having serious issues calling a post request from the django view. my login function - with schema_context(restaurant_schema): app = Application.objects.first() #return Response({'domain': domain_name, 'client_id': app.client_id, 'client_secret': app.client_secret,}) domain_name = 'http://localhost:1337/o/token/' headers = {'content-type': 'application/json' } r = requests.post(domain_name,headers=headers, data={ 'grant_type': 'password', 'username': email, 'password': password, 'client_id': app.client_id, # 'scope': 'read', 'client_secret': app.client_secret, },) This works fine on on manage.py runserver. but whenever Gunicorn and nginx are added to the mix it throws ConnectionError at /login HTTPConnectionPool(host='localhost', port=1337): Max retries exceeded with url: /o/token/ (Caused by NewConnectionError(': Failed to establish a new connection nginx.conf : upstream example { server web:8000; } server { listen 80; #server_name localhost; location / { proxy_pass http://example; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_read_timeout 300; proxy_connect_timeout 300; proxy_send_timeout 300; } } docker-compose file: services: web: build: context: ./ dockerfile: Dockerfile.prod command: gunicorn ExampleLiteB.wsgi:application --bind 0.0.0.0:8000 --workers 3 # volumes: # - static_volume:/home/app/web/staticfiles # - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:14.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - static_volume:/home/app/web/staticfiles ports: - 1337:80 depends_on: - web networks: djangonetwork: driver: bridge volumes: postgres_data: static_volume: … -
Can't find Django Shell command to purge records from one table, where matching records DON'T exist in another table
Django / ORM I have two tables, and I'm trying to purge / find all records in one table, where no matching records exist in the matching table. I'm using the Django Shell to test, but can't figure the command to say (in plain English)... Delete/Show all records in my movie table where there are no ratings for it in the ratings table The Movie table (obviously) has an id field, and the Rating table has a matching FK movie_id field) The tables are: class Movie(models.Model): imdbID = models.TextField(unique=True) title = models.TextField() year = models.TextField() class Rating(models.Model): movie = models.ForeignKey(Movie,on_delete=CASCADE) user = models.ForeignKey(User,on_delete=CASCADE) rating = models.IntegerField() A few of the Django commands I have ran are (to try to get close): >>> Movie.objects.all() ;gives all movies >>> Rating.objects.all() ;gives all ratings >>> Rating.objects.filter(movie__year=2018) ;works But when i try to dig deeper: (trying to ask for movies where movie_id equals rating movie_id), i get stuck... >>> Movie.objects.filter(movie_id=rating__movie) Traceback (most recent call last): File "", line 1, in NameError: name 'rating__movie' is not defined >>> Movie.objects.filter(rating__movie=movie_id) Traceback (most recent call last): File "", line 1, in NameError: name 'movie_id' is not defined I really want the NOT "WHERE' condition, but I can't … -
HTMX-How can I get valid form when field "keyup changed"
I have a forms.py as following. I am using htmx for validation. And I would like to get whole form for use form.is_valid() function. But in my case I am getting no valid form. Is there any way to get all form with HTMX? forms.py class UniversityForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'university-form' self.helper.attrs = { 'hx-post': reverse_lazy('index'), 'hx-target': '#university-form', 'hx-swap': 'outerHTML' } self.helper.add_input(Submit('submit', 'Submit')) subject = forms.ChoiceField( choices=User.Subjects.choices, widget=forms.Select(attrs={ 'hx-get': reverse_lazy('check-subject'), 'hx-target': '#div_id_subject', 'hx-trigger': 'change' }) ) date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'type': 'date', 'max': datetime.now().date()})) class Meta: model = User fields = ('username', 'password', 'date_of_birth', 'subject') widgets = { 'password': forms.PasswordInput(), 'username': forms.TextInput(attrs={ 'hx-get': reverse_lazy('check-username'), 'hx-target': '#div_id_username', 'hx-trigger': 'keyup[target.value.length > 3]' }) } def clean_username(self): username = self.cleaned_data['username'] if len(username) <= 3: raise forms.ValidationError("Username is too short") return username def clean_subject(self): subject = self.cleaned_data['subject'] if User.objects.filter(subject=subject).count() > 3: raise forms.ValidationError("There are no spaces on this course") return subject def save(self, commit=True): """ Hash user's password on save """ user = super().save(commit=False) user.set_password(self.cleaned_data['password']) if commit: user.save() return user views.py def check_username(request): form = UniversityForm(request.GET) if form.is_valid(): print('Valid') else: print('No Valid') print(form.errors) print(form['date_of_birth']) context = { 'field': as_crispy_field(form['username']), 'valid': not form['username'].errors } return render(request, 'partials/field.html', context) Error: … -
How to accelerate the landing web page using Django on Digitalocean?
I created a "landing page website" using Django, it's a very simple website for using just for showing up the data with no query sets that coming from the database it's just 3 or 4 queries. I'm using the Nginx server for deploying and everything working properly but just the loading of the page is very very slow, I don't know where can I find the issue. I thought that the problem might become from Nginx since it has the ability to manage static files and also, I thought about maybe droplet cause such that issue. my brain is frozen about finding the core of that problem where I can't think of where the problem may happen so, how can I accelerate my web page, and what are the reasons for that problem? I don't know if StackOverflow is a good choice to ask such that question or not but I will be grateful for solving that problem in advance -
Get value from ajax to view template without using form
I have a div class that get content from for loop queryset <div class="form-group row"> <div class="col-md-4">Số hợp đồng</div> <label class="col-md-8" id="so_hd_goc">{{hd.so_hd}}</label> </div> I want to use ajax to get the value from id="so_hd_goc" and send it to views: my views: def check_so_hd(request): check_shd=request.GET.get("check_shd") print("check_shd",check_shd) return HttpResponse(check_shd) my form: <div class="card card-body"> <form method="POST" id = "save_bo_sung_sdt"> {% csrf_token %} <div class="form-group row"> <div class="col-md-6">Người liên hệ</div> <div class="col-md-6" id ="sdt_nguoi_lien_he" name="sdt_nguoi_lien_he">{{form1.nguoi_lien_he}}</div> </div> <div class="form-group row"> <div class="col-md-6">Số điện thoại</div> <div class="col-md-6" id ="sdt_dien_thoai" name="sdt_dien_thoai">{{form1.dien_thoai}}</div> </div> <div class="form-group row"> <div class="card-footer" > <button type="submit" class="btn btn-primary" id="save_phone" name="save_phone">Lưu số điện thoại</button> </div> </div> </form> </div> my ajax: <script> const form1 = document.getElementById('save_bo_sung_sdt') const sdtContainer = document.getElementById('sdt-body') form1.addEventListener('submit', checkshd) function checkshd(e){ e.preventDefault() check_shd=document.getElementById(so_hd_goc) $.ajax({ type: "GET", url: "{% url 'check_so_hd' %}", data: { check_shd:check_shd }, success:function(data){ alert(data) } }) }; </script> my url path('check_so_hd', CallerViews.check_so_hd, name="check_so_hd"), There is no error> just not print any result -
Should Response be imported or mocked when using unittest.mock
I'm learning unittest and unittest.mock with the latter not quite clicking. I'm mocking the response of an end-point and had the following: import unittest from unittest.mock import patch from rest_framework.test import APIClient class CoreTestCase(unittest.TestCase): @patch('core.views.CoreViewSet.list') def test_response(self, mock_get): mock_get.return_value = [{'hello': 'world'}] client = APIClient() response = client.get('/core/') print(response.data) Which resulted in the following error: AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'list'>` Made sense because DRF uses Response. To get around the error I modified to: import unittest from unittest.mock import patch from rest_framework.test import APIClient from rest_framework.response import Response class CoreTestCase(unittest.TestCase): @patch('core.views.CoreViewSet.list') def test_response(self, mock_get): mock_get.return_value = Response([{'hello': 'world'}]) client = APIClient() response = client.get('/core/') print(response.data) Which achieved the desired result and I was just passing in an array of objects (or list of dicts). However, I'm not sure this was the correct way of handling this and if Mock() should have been used instead. I can honestly say I haven't been able to figure out how to use Mock() or MagicMock() correctly, or find a tutorial that explains it clearly, so my attempts at using it with: mock_get.return_value = Mock([{'hello': 'world'}]) Just resulted in: TypeError: 'module' object … -
Error when trying to authenticate via Django allauth social login when using in app browser on Instagram or Facebook messenger
My website work fine in a regular browser, but when visiting it trough a in app browser from either Instagram of faceboon messenger it stops working. When visiting trough the faceboon messenger app nothing happens when clicking the Facebook authenticate button, and clicking the Google button raises the error: Error 400: redirect_uri_mismatch When visiting trough the Instagram in app browser the Facebook login seems to work as expected but the Google login raises the same 400 error. Using the slack in app browser things work as expected. Any ideas what the issue can be here and how to resolve it? -
django custom sign up form with dropdown field, allauth
so, I am using django allauth with custom signup form and page. I am trying to make usermanager to pickup vendor name and vendor code on signup page from vendorinfo class. So if I select vendor name on dropdown box on sign up page, it should automatically select vendor code that matches with vendor name field. How can I accomplish this? This is all auth so I didn't even need to create view for signup page. it just picks up signup.html from my template to generate form. forms.py class MyCustomSignupForm(SignupForm): name = forms.CharField(max_length=30, label='Name') vendor_name = dropdown vendor_code = dropdown that matches with vendor name model.py class VendroInfo(models.Model): vendor_code = models.IntegerField('Vendor Code', primary_key=True) vendor_name = models.CharField('Vendor Name', max_length=50) class UserManager(BaseUserManager): def _create_user(self, name, vendor_name, vendor_code, password): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( name = name, vendor_name=vendor_name, vendor_code=vendor_code ) user.set_password(password) user.save(using=self._db) return user def create_user(self, name, vendor_name, vendor_code, password): return self._create_user(self, name, vendor_name, vendor_code, password) -
Django conditional inserts in multiple fields
I have two Django model: Object and Purchases. On the Object model, there are two fields: date_most_recent_purchase and date_first_purchase. I am inserting many dictionnaries, and each dictionnary can have the following values (of course, the date and object_id can be any value): {"object_id": 1, "date_purchase": None, "date_first_purchase": None} {"object_id": 1, "date_purchase": None, "date_first_purchase": "2020-11-11"} {"object_id": 1, "date_purchase": "2019-12-12", "date_first_purchase": None} {"object_id": 1, "date_purchase": "2018-2-10", "date_first_purchase": "2018-2-2"} Below are my Django models: class Object(models.Model): object_id = models.IntegerField(unique=True) date_first_purchase = models.DateField(null=True) date_most_recent_purchase = models.DateField(null=True) # this second model is not very important here class Purchase(models.Model): purchase_id = models.IntegerField(unique=True) date_purchase = models.DateField(null=True) (For a given object_id, I have many purchases) I would like to define some rules: if for a given object_id, there is no date_most_recent_purchase (= null) in DB, but a date_first_purchase in the dictionary (such as {"object_id": 1, "date_purchase": None, "date_first_purchase": "2020-11-11"}), we should set the value of date_first_purchase in DB for field date_most_recent_purchase. We should apply the same logic in the other case: date_first_purchase is null in DB, and dictionary contains a value such as {"object_id": 1, "date_purchase": "2019-12-12", "date_first_purchase": None} If date_first_purchase is set in DB, but the dictionary contains a value with a lower value of date_first_purchase, we … -
How to create multiple objects using django formset
Googling, I succeeded in creating multiple objects in one page using formset in Django. But I want to add all fields from Class Model 'Supporting' to form. The code below is a form that accepts only the 'hour' field. If I enter fields except for the 'hour' field once, I want it to be saved as the same value as the hour field is added. In other words, I want all fields to be input and only the 'hour' field to be added when needed. How do I add the rest of the fields? forms.py? I've tried several things for several days, but it doesn't work. please help.... [models.py] class Supporting(models.Model): date = models.DateTimeField(blank=True, null=True) student = models.ForeignKey(Student, on_delete=models.CASCADE, blank=False, null=True) kinds = models.CharField(max_length=50, choices=KINDS_CHOICES, blank=True, null=True) hour = models.CharField(max_length=2, blank=True, null=True) teacher = models.CharField(max_length=50, blank=True, null=True) comment = models.TextField(blank=True, null=True) [forms.py] from django import forms from django.forms import modelformset_factory, ModelForm, DateTimeInput from .models import Supporting SupportingModelFormset = modelformset_factory( Supporting, fields=('hour',), extra=1, widgets={'hour': forms.TextInput(attrs={'class': 'form-control'}), 'date': forms.DateTimeInput(format=('%Y-%m-%d %H:%M'), attrs={'autocomplete': 'off', 'type': 'datetime'}) } ) [views.py] def add_supporting(request): if request.method == 'GET': formset = SupportingModelFormset(queryset=Supporting.objects.none()) elif request.method == 'POST': formset = SupportingModelFormset(request.POST) if formset.is_valid(): for form in formset: if form.cleaned_data.get('hour'): form.save() … -
Djagno rest view file structure with complex calculations
I'm writing django rest api. I'll be taking form which will be sent from frontend. Form will contain data which I'll be using for performing calculation. But there is a problem. Based on form data code should execute different calculation types. So for example form { "type": 1, "form": 3, "method": } Then I should read "type". It should lead rest of form to another View method called for example type1. Then using "form" it should go for another view method form3 etc. Should I write that long api views methods or maybe I should create another file for performing calculations based on form data? Example (I will not attach serializer validation etc there): class SubmissionView(APIView): def post(self, request): if request['type'] == 1: self.type1(request.data) elif request['type'] == 2: self.type2(request.data) ........ def type1(self, request_data): if request['form'] == 1: self.form1(request.data) elif request['form'] == 2: self.form2(request.data) etc... -
Create Django URL inside JS function based on 3 different models
I have a function that displays titles from 3 different models in Django. I want to add a link to each title so it redirects the user to the proper URL. The search_autocomplete function returns all titles properly in 1 list, however, I am struggling with the creation of the URL address in the js file. I am using this library to create a list of titles. Let's say that the user puts "python is amazing" in the search bar. The URL address should contain rootURl/modelUrl/slug. If the title comes from the article model then it should look like this: http://127.0.0.1:8000/article/python-is-amazing If the title comes from the qa model then it should look like this: http://127.0.0.1:8000/qa/python-is-amazing If the title comes from the video model then it should look like this: http://127.0.0.1:8000/video/python-is-amazing The second issue is that I want to display a list of titles in autocomplete list but I need to pass the slug field to the URL address. How can I do that? js file //root URL const rootUrl = 'http://127.0.0.1:8000' //models URLs const articleURL = 'article' const qaURL = 'qa' const videoURL = 'video' new Autocomplete('#autocomplete', { search: input => { const url = `/search/?title=${input}` return new Promise(resolve … -
CKEditor Content not rendering
I am using CKEditor to display blog post descriptions using Django. I try to render the description field variable onto a HTML page using {{thread.description|safe}} which I have read I should use instead of just {{thread.description}} but it only renders the source code. E.g Render Bold Result I also get the same result when trying to render out images Render image Result My editor appears to handle this fine Editor Input Any suggestions? Thank you -
django: how to add slug as arguments in url tag using django
i want to add slug in url using django like this <a href="{% url 'base:tutorial-page' p.slug p.slug2 %}" </a> i dont really know how to pass in double slug in the url for example: i want to access the html page before going to the tutorial page related to html. getting-started.html {% for p in prglangcat %}> {{ p.title }} <a href="{% url 'base:tutorial-page' p.slug p.slug %}" </a> {% endfor %} strong text def gettingStarted(request): prglangcat = ProgrammingLanguagesCategory.objects.all() context = { 'prglangcat': prglangcat } return render(request, 'base/getting-started.html', context) def programmingLanguageTutorial(request, prg_slug): prglangcat = ProgrammingLanguagesCategory.objects.get(slug=prglangcat_slug) prglangtut = ProgrammingLanguageTutorial.objects.get(slug=prg_slug, prglangcat=prglangcat) context = { 'prglangtut': prglangtut } return render(request, 'base/tutorial-page.html', context) models.py class ProgrammingLanguagesCategory(models.Model): title = models.CharField(max_length=100) icon = models.ImageField(upload_to='programming-category', default="default.jpg") description = models.TextField(default="Learn ...") slug = models.SlugField(max_length=100, unique=True) def get_absolute_url(self): return reverse('programming-languages-category', args=[self.slug]) def __str__(self): return self.title class ProgrammingLanguageTutorial(models.Model): prglangcat = models.ForeignKey(ProgrammingLanguagesCategory, on_delete=models.CASCADE, null=True) slug = models.SlugField(max_length=10000, unique=True, null=True) title = models.CharField(max_length=10000) description = models.TextField(null=True) image = models.ImageField(upload_to='Tutorial Image', default="default.jpg", null=True) code_snippet = models.CharField(max_length=1000000000, null=True, blank=True) video_url = models.URLField(null=True) views = models.IntegerField(default=0) def __str__(self): return self.title urls.py app_name = 'base' urlpatterns = [ path('', views.index, name="index"), path('getting-started/', views.gettingStarted, name="getting-started"), path('getting-started/<slug:prglangcat_slug>/<slug:prg_slug>', views.programmingLanguageTutorial, name="tutorial-page"), ] traceback NoReverseMatch at /getting-started/ Reverse for 'tutorial-page' with no … -
Unable to use dash_bio for plotting ideograms due to incorrect Javascript dependency
I am trying to include dash_bio ideogram in my proyect. I have just included in my project a simple ideogram as follows: dashbio.Ideogram( id='ideogram-id', chromosomes=['X'], orientation='horizontal', ), There are no callbacks for this ideogram, I am just trying the simplest example for an indeogram. The error I get on my console when trying to plot it is the following: bundle.js:1 GET https://unpkg.com/dash-bio@1.0.1/dash_bio/async-alignment.js net::ERR_ABORTED 404 When visiting the link, I can see that the requested JS does not exist: Cannot find "/dash_bio/async-alignment.js" in dash-bio@1.0.1 Is there any way to solve this issue? -
Django cannot response json data
I create device function in views.py for return json data like this. views.py def device(request): responseData = { 'id': 4, 'name': 'Test Response', 'roles' : ['Admin','User'] } return JsonResponse(responseData) I set url path to views.device() in urls.py like this. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('device/', views.device()), ] when I save project it show error like this. How to fix it? File "C:\Users\MAX\Django\test_project\test\test\urls.py", line 23, in <module> path('device/', views.device()), TypeError: device() missing 1 required positional argument: 'request' -
How to handle Firebase Cloud Messaging Notifications in Django?
I am managing to send FCM notifications to my app through Django. Here is my function for pushing notifications: import firebase_admin from firebase_admin import credentials, messaging cred = credentials.Certificate("service-key.json") firebase_admin.initialize_app(cred) def send_push(title, msg, registration_token, dataObject=None): try: message = messaging.MulticastMessage( notification=messaging.Notification( title=title, body=msg, ), data=dataObject, tokens=registration_token, ) response = messaging.send_multicast(message) except messaging.QuotaExceededError: raise f'Exceeding FCM notifications quota' Now, I'll be sending a Notification inside a view: class AdminChangeRole(viewsets.Viewset): serializer_class = SomeSerializer permission_classes = [IsAdminOnly] def post(self, request, *args, **kwargs): # code that will change the role of a user send_push("Role changed", f"You role was set to {self.role}", fcm_registration_token) # return Response Now, after posting some data inside a serializer and save it. I'm hoping to send a notification for a User. However, I want to know if I am handling this correctly, including the 2500 connections in parallel and 400 connections per minute. -
ConsumptionClient reservations_summaries.list error of MissingSubscription
Package Name: ConsumptionManagementClient Package Version: 9.0.0 Operating System: IOS Python Version: 3.7 Describe the bug After updating the creds for app registration as described here: https://docs.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#cost-management-reader I am facing the same error: '(MissingSubscription) The request did not have a subscription or a valid tenant level resource provider. Code: MissingSubscription Message: The request did not have a subscription or a valid tenant level resource provider.' To Reproduce Steps to reproduce the behavior: from azure.mgmt.consumption import ConsumptionManagementClient credentials = retrieve_creds() subscription_id = 'XXXXXXXXXXXXXXX' consumption_client = ConsumptionManagementClient( credentials, subscription_id, 'https://management.azure.com' ) scope = subscription_id reservation_generator = consumption_client.reservations_summaries.list(scope=scope, grain='monthly') for reservation in reservation_generator: print(reservation) Expected behavior I expected that in subscription_id which has the required creds, I will be able to loop on the reservation summary result. but it failed in the loop. Additional context It is pretty hard to find good documentation for consumption_summary package. If I did something wrong in the code, please reference me to relevant resource. Just to mention that consumption_client.usage_details.list(scope, filter=date_filter) worked fine.