Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
django filter gte and lte on one property of one model
I have a User model with age property my models.py class User(models.Model): age = models.IntegerField() i need to output all users between 25 and 35 i can only make query which won't exclude others users first_query = User.objects.filter(age__gte=25) second_query = User.objects.filter(age__lte=35) can i output users between 25 and 35 and exclude others, in one query? -
Dockerfile not being found for Google cloud run
I've hit another bug. I'm now trying to set up continuous deployment for Google Cloud Run from my GitHub, and it's not finding my Dockerfile. I've tried various combinations with my file paths, but it still gives me the Already have image (with digest): gcr.io/cloud-builders/docker unable to prepare context: unable to evaluate symlinks in Dockerfile path: lstat /workspace/Dockerfile: no such file or directory error. This is my file structure from VSCode, and if I run the command from the first Exeplore folder, it finds the Dockerfile The source directory is public, so I just can't figure out why it's not finding the Dockerfile. https://github.com/Pierre-siddall/exeplore Any advice at all would be greatly appreciated, thank you! -
django eventstream / channels return HTML
I have a working application where I use django-eventstream to show info/error messages to users. All works well with send_event(): send_event("ok_message", "message_ok", msg) send_event("error_message", "message_error", msg) but what I actually want to do is send some html directly to the frontend. Is this possible? send_event("ok_message", "message_ok", {"html": "<h1>test</h1>"}) -
How to add item to cart after the user login ? #django
I'm completely new to Django and I tried to create a simple eCommerce web application. In my code, when the user is not logged, items are easily added to the cart and displayed to the web application but when the same user logged into the application and tries to add the item to the cart it is not displayed in the frontend but the item is added to user from backend. I tried the logic if user.is_authenticated but I was not able to succeed. from carts.models import Cart, CartItem def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart, ) cart_item.save() return redirect('cart') This is Django code adding items to the cart before the user login. -
NEED TO SHOW PROGRESS BAR OF FILE SPLITER FUNCTON IN PYTHON
I have a web application that split large CSV into multiple CSV. But I need to show the progress of function processing to the user on front end. Can anyone help me with that, I am using python and Django -
How to extend multiple bases or conditional {% extends %} in one html page in django?
{% if request.user.profile.emp_desi in qa_list %} {% extends "qa_base.html" %} {% elif request.user.profile.emp_desi in mgr_list %} {% extends "manager_base.html" %} {% else %} {% extends "common_base.html" %} {% endif %} How can I solve this problem?? based on designation I want to extend different different bases. -
Why Django doesn't update an object?
I have a model Profile, which connects with User. For example I have Testuser. When I try to update his field 'money', nothing happens. I suppose it may be because I use User, instead of Profile in get_object. But if I change it to Profile, there is an error, that Profile doesn't have username field. How can I solve this problem? model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) money = models.IntegerField(default=0) form: class AddMoneyForm(forms.ModelForm): class Meta: model = Profile fields = ('money',) view: class AddMoneyView(UpdateView): model = Profile template_name = 'users/money.html' fields = ['money'] def get_object(self, queryset=None): return get_object_or_404(User, username=self.kwargs.get('username'), pk=self.request.user.pk) def get_success_url(self): return reverse('account', kwargs={'username': self.request.user.username}) url: path('account/<str:username>/money/', AddMoneyView.as_view(), name='money'), -
How to use the result of a graphene resolved field in another field
I have this use case: class ProjectType(graphene.objectType): tasks = graphene.List(TaskType) duration = graphene.Int() # days def resolve_tasks(): return self.tasks.all() def resolve_duration(): return get_duration_from_tasks(self.tasks.all()) A project can have many tasks, so self.tasks.all() can be an expensive db query to do twice. -
Is it necessary to do threading for sending emails in django
I am not sure that if it is necessary to use thraeding for sending emails in django or not ? If we need to do it so Can i just use the threading library instead of Celery or rabbitmq ? -
Django Form | Group Model | MultiSelect | getting only single value from the form by using MultiSelect widget
I am trying to get input from the user in a template, I am showing list of Groups in template available from the Group model in Django Auth Models and expecting multiple values. But it is only returning single value even selecting multiple options from django.contrib.auth.models import Group class MyForm(forms.ModelForm): the_choices = forms.ModelMultipleChoiceField(queryset=Group.objects.all(), required=False, widget=forms.CheckboxSelectMultiple) class Meta: model = Group exclude = ['name', 'permissions'] def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) image references below Template - Input Form Image Output in Console kindly refer to image 2, I expect 1 and 2 (group name preffered) in console but its returning only 2. -
JWT with Django Rest Framework not working in production
My application uses Django Rest Framework for the APIs and JWT for authenticating the users. Everything was working fine in my local machine. I started having problems after a deployed it to an EC2 instance. The only things that still work are the login, registration and tokens refresh. That is, when I try to log in, I receive the tokens back from the back-end, which are successfully stored in the local storage; when I try to sign up, the back-end creates the new user; and from time to time the tokens are also successfully updated. But all the other API calls fail. At the beginning, when I made an API call, I was getting back "401 Unauthorized". I believe the reason was because Apache wasn't forwarding the Authorization-Headers. So I added "WSGIPassAuthorization On" to the Apache configuration. Now I am getting "500 Internal Server Error" instead. As I already said, only API calls to login, tokens refresh and registration are working. For login and tokens refresh, I am using the default "TokenObtainPairView" and "TokenRefreshView". from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ path('log-in/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('refresh-token/', TokenRefreshView.as_view(), name='token_refresh'), ] For the registration, this is the view I am using: class … -
django - disable button in javascript based on text input
I've got problem to disable submit button conditionally. My js code is as follows: function disableButton() { var btnSubmit = document.getElementById('sub_butt'); if (document.getElementsByName('submitted').value == "yes") { btnSubmit.disabled = true; } else { btnSubmit.disabled = false; } } In django I have updateForm with formset and I would like to disable button based on value text field with name "submitted". I've tried the code above but nothing's changed. Field "submitted" is already filled out with value 'yes' -
ModelFormset in Django CreateView
I'm still new to Django & I would like to know how can allow user to add more than 1 ReferrerMember on Registration form as I wanted to achieve similar to the image url below https://imgur.com/a/2HJug5G I applied modelformset but so far it's giving me an error where "membership_id" violates not-null constraint the moment I submitted the form. I've searched almost everywhere to find how to implement this properly especially on class-based view instead of function based view but still no luck. If possible please help me point out on any mistakes I did or any useful resources I can refer to models.py class RegisterMember(models.Model): name = models.CharField(max_length=128) email = models.EmailField() class ReferrerMember(models.Model): contact_name = models.CharField(max_length=100) company_name = models.CharField(max_length=100) membership = models.ForeignKey(RegisterMember, on_delete=models.CASCADE) forms.py class RegisterMemberForm(ModelForm): class Meta: model = RegisterMember fields = ['name', 'email', ] class ReferrerForm(ModelForm): class Meta: model = ReferrerMember fields = ['contact_name ', 'company_name ', ] ReferrerMemberFormset = modelformset_factory(ReferrerMember, form=RegisterMemberForm, fields=['contact_name ', 'company_name ', ], max_num=2, validate_max=True, extra=2) views.py class RegisterMemberView(CreateView): form_class = RegisterMemberForm template_name = 'register.html' def post(self, request, *args, **kwargs): member_formset = ReferrerMemberFormset (request.POST, queryset=ReferrerMember.objects.none()) if member_formset .is_valid(): return self.form_valid(member_formset ) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['member_formset'] = ReferrerMember(queryset=ReferrerMember.objects.none()) return context register.html <form …