Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ckeditor Tool icons are not showing
I installed django-ckeditor using pip install django-ckeditor. while using it in the normal page (I created a html and inserted the form.media and form to get the editor there) everything worked but the icons in the toolbar are not appearing in the page where I wanted to use it. Note: I am able to use it properly in admin page and the icons are also appearing. Icons here are not appearing but the functionality is working i.e, 'Ctrl+B' works for etc.. Image: Files are: In the settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'accounts', 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_UPLOAD_PATH = '' STATIC_URL = '/static/' STATIC_ROOT = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = 'media/' In the models.py file: from django.db import models from ckeditor_uploader.fields import RichTextUploadingField class Message(models.Model): msg = RichTextUploadingField(blank=True, null=True) cid = models.ForeignKey(Car, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) def __str__(self): return f"{self.id}:{self.msg[:6]}" In the forms.py file: from django.db.models import fields from django.db.models.base import Model from django.forms import ModelForm from .models import Message class MessageForm(ModelForm): class Meta: model = Message fields = ['msg','cid'] In the html: <form method="POST"> {% csrf_token %} {{ form.media }} {{ form }} <button class="btn btn-secondary">Post</button> </form> -
paypal.HostedFields.isEligible() returns False always : Paypal Debit/Credit Card Payment
I want to include debit/credit card payments powered by papal for my website, I am following the guide as per https://developer.paypal.com/docs/business/checkout/advanced-card-payments/ but for the code paypal.HostedFields.isEligible() I always get the false or undefined as error, may be I skipped something, please help. -
How to correctly get variables from Django to javascript and do a GET ajax call on a Django URL?
I apologize if I butchered the terms there. I'm learning webdev and I still don't understand how these technologies work together, so I'm writing everything that might contribute to the problem. Here's where I'm at right now: The urlpatterns in sites/urls.py: urlpatterns += [ path('api/test/<str:crop>/<str:category>/<str:date_from>/<str:date_to>/', data.get_test_page_data), path('test/<str:item>/<str:category>/<str:date_from>/<str:date_to>/', data.render_initial_test_page) ] The functions in data.py: def get_test_page_data(item, category, date_from, date_to): date_from = datetime.datetime.strptime(date_from, "%Y-%m-%d") date_to = datetime.datetime.strptime(date_to, "%Y-%m-%d") data = Items.objects.all().filter(item=item, category=category, date__range=[date_from, date_to]) context = { "data" : data, } return JsonResponse(context) def render_initial_test_page(response, item, category, date_from, date_to): ... context = { "item" : item, "category" : category, "date_from" : date_from, "date_to" : date_to } return render(response, 'sites/test.html', context) The test.js: var sites, map; var test_data; var item = '{{ item }}'; var category = '{{ category }}'; var date_from = '{{ date_from }}'; var date_to = '{{ date_to }}'; getTestData(); function getTestData() { $.ajax({ method: 'GET', url: '/api/test/' + item + '/' + category + '/' + date_from + '/' + date_to + '/', success: function(data) { test_data = data; renderTestData(); } }); } The problem: It doesn't work. It should render two objects in the test page, one Google Maps with markers on where the item is last seen … -
How to print filtered results from django model
I am trying to print the filtered results from a django model. This is my code record = StudentInfo.objects.filter(Name=name, School=school, City=city, Country=country) I know there are 4 entries that satisfy the filter. I now want to print the records. But when I try print(record) I get the following [<StudentInfo: StudentInfo object (1)>, <StudentInfo: StudentInfo object (4)>, <StudentInfo: StudentInfo object (6)>, <StudentInfo: StudentInfo object (8)>] How do I print the entire record as a list? -
Django Celery background scraper
I need some help, My setup is Django, Postgres, Celery, Redis – all dockerized. Besides regular user-related features, the app should scrape info in the background mode. What I need is to launch the scraping function manually from management command like "python manage.py start_some_scrape --param1 --param2 ..etc", and know that this script works in the background mode informing me only by logs. At this moment script works without Celery and only while the terminal connection is alive what is not useful because the scraper should work a long time – like days. Is Celery the right option for this? How to pass a task from management command to Celery properly? How to prevent Celery to be blocked by the long-time task? Celery also has other tasks – related and not related to the scraping script. Is there are threads or some other way? Thx for help! -
How to pass a javascript constant to django?
Usually, you pass Django vars to HTML templates but today I want to do the opposite. I have a custom tag in javascript and I need to pass it back to handle it inside Django. @register.filter(name='test_alerst') def test_tags(value, arg): return MyFunction(val) goalg pass myConst to the function test_tags % load test_tags %} <!doctype html> <html lang="en"> <body> <button id='botton'>socket.send</button> <script> const myConst = javascriptThings {% with name= myConst %} {{ token|test_alerst:name }} {% endwith %} Error: django.template.exceptions.TemplateSyntaxError: 'with' expected at least one variable assignment -
Prevent Django from Removing Previous Entries in PostgreSQL
I have the following Django code that is being run on PostgreSQL and Huey (an automatic scheduler). The problem is that, whenever the periodic task is run, Django removes the previous rows in a table instead of adding on to existent ones. Scheduled code: @periodic_task(crontab(minute='*/1')) def scheduled(): team = nitrotype.Team('PR2W') team_id = team.data["info"]["teamID"] timestamp = datetime.datetime.now() for members in team.data["members"]: racer_id = members["userID"] races = members["played"] time = members["secs"] typed = members["typed"] errs = members["errs"] rcd = RaceData( racer_id=racer_id, team_id=team_id, timestamp=timestamp, races=races, time=time, typed=typed, errs=errs ) rcd.save() Basically, the above code is going to run every minute. Here's the database (PSQL) data that I started with: nttracker=# TABLE data_racedata; racer_id | team_id | timestamp | races | time | typed | errs ----------+---------+------------+--------+---------+----------+-------- 35051013 | 765879 | 1623410530 | 4823 | 123226 | 793462 | 42975 35272676 | 765879 | 1623410530 | 8354 | 211400 | 1844434 | 38899 36690038 | 765879 | 1623410530 | 113 | 2849 | 16066 | 995 38486084 | 765879 | 1623410530 | 34448 | 903144 | 8043345 | 586297 38625235 | 765879 | 1623410530 | 108 | 2779 | 20919 | 1281 39018052 | 765879 | 1623410530 | 1908 | 48898 | 395187 | … -
django: how to calculate percentile of each value
I have a model class TestResults(models.Model): name = models.CharField(max_length=256) score = models.FloatField() Now how to add percentile column using annotate the procedure for calculating percentile of each value Percentile = (number of values below score) ÷ (total number of scores) x 100 I know we can use annotate from django.db.models import F total = TestResults.objects.all().count() TestResults.objects.annotate(...) <-- here how to get number of values below -
Django models - year and monthly fields
I am developing a system using Django 3.0, I need to change balance values on a monthly basis but still have the previous value for displaying on the statement example bills statements.. how best can write my models -
Which field use in a model if I need store several elements in one field?
I try to create a model cart on my shop site. It model should contain the product names. class Cart(models.Model): products = models.Field() Cart.products = 'ps5', 'tv', 'keyboard' -
Django seems to not escape XSS attacks?
I will appreciate your help in this so much, I am developing a Django application and everything is fine and working. I was reading yesterday about security breaches and how django templates permit to block dangers like csrf, xss...etc. So I wanted to test my app if it does escape an xss attempt before I move on with my app and duplicate my models, forms, and views. What I did was that I have entered as input <script alert("xss"); in one of my forms (POST), pressed the submit button, and checked the entered instance in a list view. My problem is that it was there with the exact same input without any sort of encrypting from Django. Yes, the javascript didn't get executed and no alert message showed, but isn't Django supposed to escape/encript html tags? I have also inspected the code source behind and, similarly, the result is exactly as I have entered it. The same thing in the database. The input is stored as it is without escaping the html tags. Am I missing something or it is how it's supposed to be? My product view in views.py def add_product(request): pharmacy = Pharmacy.objects.get(id=1) form = ProductForm(initial={'pharmacy':pharmacy}) if request.method=='POST': … -
ckeditor django no error but don't show editor
I trial make editor for my blog django when used django_summernote work good but when ckeditor django no error but don't show editor so how fix it forms.py when used SummernoteInplaceWidget show but when used CKEditorWidget don't show and textarea input hiden from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget from ckeditor.widgets import CKEditorWidget class NewTopicForm(forms.ModelForm): # content = forms.CharField(widget=SummernoteInplaceWidget()) content = forms.CharField(widget=CKEditorWidget()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['author'].widget.attrs.update( {'class': 'd-none'}) self.fields['author'].label = '' self.fields['author'].required = False self.fields['slug'].required = False class Meta: model = Topic fields = ('title','image', 'author', 'content','NotfFaV','slug') widgets = { 'title': forms.Textarea(attrs={'class': 'ml-3 mb-3 form-control border-0 read-more rounded-0', 'rows': '1', 'placeholder': 'اضف تعلق'}), } urls.py path('ckeditor/', include('ckeditor_uploader.urls')), views.py def home(request): topic_form = NewTopicForm() return render(request, 'forum/home.html', { 'topic_form': topic_form }) home.html {{topic_form.media}} {{topic_form.content}} -
Throttle in Django Rest Framweork if user is None during Oauth2 request with CLient Credentials
I am using Django Rest Framework with Django OAuth Toolkit for allowing external organization to request endpoints. I am using Crendentials Client grant type to ask access token.enter image description here When i try request my endpoint I have this error : 'NoneType' object has no attribute 'is_authenticated'. The exception is raised in the get_cached_key function of the AnonThrottleClass. In fact request.user is None with Client Credentials, so this function can not pass. Here is my viewset : class StudentViewSet( mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet,): serializer_class = StudentSerializer authentication_classes = (OAuth2Authentication,) permission_classes = (TokenHasScope,) required_scopes = [ oauth2_settings.READ_SCOPE, oauth2_settings.WRITE_SCOPE, ] schema = is_schema_for_open_api_doc(True) queryset = Student.objects.all() Can you help me with this ? Thank you ! -
How do you turn a user into staff?
Using a view i want to turn a user into staff, how do i do it. using is_staff just gives me if the user is staff or not. def createAdmin(request,member_id): admin_group= Group.objects.get(name='admin') member = get_object_or_404(Member,pk=member_id) user = User.objects.get(member = member) admin_group.user_set.add(user) user.staff=True user.save() This is the code i use to make that user a admin but i don't know how i could give him staff status. user.staff doesn't work. -
Social Network Login Failure django allauth with discord
I am trying to integrate discord social account to my django project login.html: {% extends 'base.html' %} {%load crispy_forms_tags %} {% load socialaccount %} {% block content %} <div class='content-section card bg-dark p-4'> <form method='POST' autocomplete="off" > {% csrf_token %} <fieldset class='form-group'> <legend class='border-bottom mb-4'>Sign In</legend> {{ form | crispy }} </fieldset> <div class='form-group'> <button class='btn btn-outline-info' type='submit'>Login</button> </div> </form> <div class="border-top pt-3"> <p>Don't have an account? <a class='ml-2 btn btn-outline-info' href="{% url 'register' %}">Sign up</a></p> <a href={% url 'reset_password' %}>Forgot password?</a> </div> </div> <div class='login-buttons'> <div class='social-login'> <hr class="my-4"> <button class="btn btn-lg btn-google btn-block text-uppercase" type="submit"><a href="{% provider_login_url "google" %}"><i class="fab fa-google mr-2"></i>Login with Google</a> </div> <div class='social-login'> <hr class="my-4"> <button class="btn btn-lg btn-discord btn-block text-uppercase" type="submit"><a href="{% provider_login_url "discord" %}"><i class="fab fa-discord mr-2"></i>Login with Discord</a> </div> {{ auth_error }} </div> {% endblock content %} I have added api key and secret key via the admin panel.. I already have set up google authentication and it works fine. What is the error and how to solve it? Pls inform if any other info is needed -
How to add a prefix before the domain name in a url in django?
I want to create custom url like this http://admin:testserver.com/login/ I've been trying different ways to to achieve this but all of my efforts were in vain. After reading Django document i'm able to create a custom url where i can add a certain prefix after the domain name which look like this "http://127.0.0.1:8000/mod:add_product/" with this line of code url(r'^mod:', include('moderator.urls')), My friend was suggesting to use django_subdomains to get a somewhat similar url which would look like this "http://admin.xyz.com/loign" i was considering that as an option but django_subdomains has been abandoned since July 2019 is there any other options to create such urls? -
How to access User Profile's friends in ManyToMany field
I am building a simple social media app. AND i am trying to build a feature of adding users into post using ManyToManyField. I am trying to access profile friends in Post's model instance "add_user" for tagging user. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') friends = models.ManyToManyField("Profile",blank=True) class Post(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') add_user = models.ManyToManyField(.........) I have also tried using User.Profile.friends.all BUT it is keep showing. AttributeError: 'ReverseOneToOneDescriptor' object has no attribute 'friends' I am new in django and I have no idea how can i access user's friend in Post's model instance. Any help would be much Appreciated. Thank You in Advance. -
My Django local server is not running on Brave private window
When i try to run my local server on Brave Private Window with Tor connectivity it not running but it's running on Brave Private Window on Brave Private Window with Tor connectivity it's give me this message This site can’t be reachedThe web page at http://127.0.0.1:8000/ might be temporarily down or it may have moved permanently to a new web address. ERR_SOCKS_CONNECTION_FAILED -
Display Foreign key and ManyToMany relation in Django template
model.py class Record(models.Model): items = models.ManyToManyField(Item, blank=True) ... class Item(models.Model): PAYMENT_CLASSIFICATION = ( ('earning','Earning'), ('deduction','Deduction'), ('reimbursement','Reimbursement') ) payment_classification = models.CharField(max_length=20, null=True, choices=PAYMENT_CLASSIFICATION) user_to_input = models.CharField(max_length=20, null=True) ... class EachRowItem(models.Model): item = models.ForeignKey(Item,on_delete=models.SET_NULL, null=True) record = models.ForeignKey(Record,on_delete=models.SET_NULL, null=True) paid_amount = models.DecimalField(max_digits=10, decimal_places =2, null=True, blank=True ) unit = models.DecimalField(max_digits=10, decimal_places =2, null=True, blank=True ) form.py class EachRowItemForm(forms.ModelForm): class Meta: model = EachRowItem exclude = ['record'] view.py def PayRecordUpdate(request, pk): form = EachItemForm(request.POST or None) record = Record.objects.get(pk=pk) if request.is_ajax(): item = request.POST.get('item') paid_amount = request.POST.get('paid_amount') unit = request.POST.get('unit') if form.is_valid(): record = Record.objects.get(pk=pk) instance = form.save(commit=False) instance.record = record record.items.add(item) record.save() instance.save() return JsonResponse({ 'item': instance.item, 'paid_amount': instance.paid_amount, 'unit': instance.unit, }) context ={ 'record': record, 'form':form, } return render(request, '/update_record.html', context) In the template I have a popup Modal to fill in the EachItemForm form. Therefore there is is_ajax(). I can get the valid form. Item paid amount unit Earning Item A1 2.00 2 Item A2 1.00 2 ----- ----------- ---- Deduction Item B1 -2.00 1 Item B2 -1.00 1 ----- ----------- ---- Reimbursement Item C1 2.00 1 Item C2 1.00 1 However, I having problem to render in update_record.html where the items are arranged to classification accordingly. The function has … -
Django UserCreationForm Customization
I am fairly new to django and creating a website that involves account creation. The standard form UserCreationForm is fairly ugly. My main issue with it is that it displays a list of information under the password field. It displays the code in html as follows: <ul> <li>Your password can’t be too similar to your other personal information.</li> <li>Your password must contain at least 8 characters.</li> <li>Your password can’t be a commonly used password..</li> <li>Your password can’t be entirely numeric</li> </ul> Is there any way to avoid displaying this information? Can I change some information in my custom form maybe? My forms.py for this specific form is as follows: class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField(max_length=254) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) I am unsure how to change this because it isn't an errorlist or anything like that. Any help is greatly appreciated! -
How to add possibility to add many Groups (and date_joined to them) for Person in person creation form in django?
I have a Person and Group models, also I have many-to-many relationship between them with help of third model PersonGroupMembership (I using through= argument). I created forms for Person and Group to allow user to create this objects, and its works good. But now I want to add more functionality to Person creation stage: first of all user need to have possibility to add new Group (or search for already existed), and add date_joined to this Group, and also add as much Groups as user want for this Person. Is there any step-by-step plan how to realize that? How to add this fields to forms? Do I need to turn to PersonGroupMembership model inside Person form? Do I need to add date_joined field to PersonGroupMembership model? -
Django - Using a string variable in a Q filter
I have a very similar query that works for two different types of inputs and will match on the correct column. Both queries are essentially the same except for one word, i.e. the column name. def trade_company_group(company_group): # can filter both name or alias as name will always contain 'Companies' if "COMPANIES" in company_group.upper(): return ( // Same query as below except for "name", below is "alias" Q(buy_book__entity__company_groups__name__iexact=company_group) & Q(sell_book__entity__company_groups__name__iexact=company_group) & ( ~Q(buy_book__entity__type=ENTITY.INTERNAL) | ( Q(buy_book__entity__primary_company_group__name__iexact=company_group) | Q(sell_book__entity__primary_company_group__name__iexact=company_group) ) )) return ( Q(buy_book__entity__company_groups__alias__iexact=company_group) & Q(sell_book__entity__company_groups__alias__iexact=company_group) & ( ~Q(buy_book__entity__type=ENTITY.INTERNAL) | ( Q(buy_book__entity__primary_company_group__alias__iexact=company_group) | Q(sell_book__entity__primary_company_group__alias__iexact=company_group) ) )) I don't want to duplicate code so I was hoping there was a way to substitute the column name in the query depending on my if statement. Is this possible? -
select tag onchange does not execute, function failure: Uncaught ReferenceError: ... is not defined
I'm pretty new to js. I want to execute the function buildChart when the select value changes. But I get the following error all the time. Uncaught ReferenceError: buildChart is not defined Does anybody have an idea how to solve that? Thank you very much in advance! You would be a great help!! My JS function is as follows: function buildChart() { let dropdownValue = getData.getDropdownValue(); if (dropdownValue === "All Generations") { console.log("All Generations") } else { console.log("other") } } My HTML follows here: {% extends "base.html"%} {% load static %} {% block head %} <script rel="script" type="module" src="{% static 'js/productionplan/productionplan.js' %}" defer></script> {% endblock head %} {% block body %} <select id="dropdown-pp" onchange="buildChart();" class="form-select" aria-label="Default select example"> {% endblock %} -
How connect Django administration to Firebase
I am trying to connect Django to Firebase, for moment i'm using Pyrebase and i install it with pip install Pyrebase and with that in my views.py of apps, i'm able to connect to my Firebase database and it work very fine. How should i configure settings.py file to accpet Firebase as default data base? For moment i leave SQlite as default ans i just access to my Firebase in views.py. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } Regards./ -
Subtraction of two columns on two different models by its ID
I have Two Models 1)Invoice 2)Recieved Amount class Party: party_name = models.CharField(max_length=200) class Invoice(models.Model): party = models.ForeignKey(Party,on_delete = models.CASCADE) invoice_amount = models.FloatField(default=0.0) class RecievedAmount(models.Model): party = models.ForeignKey(Party,on_delete = models.CASCADE) recieved_amount = models.FloatField(default=0.0) I want to subtract (invoice_amount) from Invoice Model - (recieved_amount) from RecievedAmount Model based on the PartyId (ForignKey) and return output as [{'party':1,'total_difference':2000},{'party':2,'total_difference':5000}] total_difference = invoice_amount - recieved_amount And also parties can be more than 100. Can you please tell me the query that performs this operation. Thanks