Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Positioning ckeditor field Django
I need to properly position the ckeditor window with css. I added a class to the field in my form: class ArticleCreateForm(forms.ModelForm): class Meta: model = Article fields = ('title', 'text', 'image') widgets = { 'title': forms.TextInput(attrs={'id': 'article_title_form'}), 'text': forms.TextInput(attrs={'class': 'article_text_form'}), } Added css: #article_title_form { position: absolute; width: 881px; height: 48px; left: 120px; top: 306px; background: #FFFFFF; border: 2px solid #CDCDCD; border-radius: 3px; } .article_text_form { position: absolute; width: 881px; height: 478px; left: 120px; top: 391px; background: #FFFFFF; border: 2px solid #CDCDCD; box-sizing: border-box; border-radius: 3px; } And it worked perfectly good for the title field, but the text field ignores css and is displayed in a top left corner of a page. What am I doing wrong? -
Can I fill Django form with jQuery?
So I have an input field, but want to fill it in with a dropdown item. I figured I'd have to do it with jQuery, but have no idea how. Here's my code : <span class="dropdown"> <button class="btn menial-buttons dropdown-toggle" id="cat-dropdown-input" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span>🔖 Category</span> </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <button class="dropdown-item" id="cat-1">Book</button> <button class="dropdown-item" id="cat-2">Drink</button> <button class="dropdown-item" id="cat-3">Play</button> </div> </span> <div class="field"> <div class="input-category">{{form.category}}</div> </div> And here's my jQuery code. I'm not very familiar with jQuery. $('.dropdown-item').click(function() { var thisCat = $(this).text(); $('#id_category').html(thisCat); }); *The id of the form field is #id_category. Thank you very much in advance :) -
Django celery beat not scheduling at Asia/Calcutta timezone
I am using Django celery beat with celery, 1: Problem which I am facing is my when I am using scheduler provided by Django-celery beat it doesn't work but using normal beat without scheduler provided by Django-celery-beat works 2: one thing I noticed when I change Time_Zone to 'UTC' Django-celery-beat scheduler starts working, how do I fix this please find my settings below USE_TZ = False TIME_ZONE = 'Asia/Kolkata' CELERY_TIMEZONE = 'Asia/Kolkata' -
How should is structure Django Blog Website with reusable applications?
I am developing a blogging site. I need help in structuring the django applications. Features i have are: 1. Blog Feed 2. Moderator Site 3. Dashboard for each author to analyse his interactions 4. Notifications for badges earned, moderation, chats, etc 5. Messenger and a few more. I am confused with how many apps do i have to make. currently i have : Blog feed notifications blog admin (for moderator to check posts are according to the code of conduct) blog editor Should the settings be a different app. Should there be a different app for dashboard. I have a few there details like saving billing information which i will be using in other projects. There are other so many things in settings site. should different settings forms like email notification and billing , organization, notification settings, themes settings be different apps. I am new to Django and i am confused with how apps work. I would like to know how i should structure the project and apps. How i can make them work with each other. -
Is it safe to use celery with non thread-safe code?
What is the best way to handle non thread-safe code with Celery? @app.task def do(): # non thread-safe code here -
Apple Sign In Python
I want to make an apple sign in with social auth python. Now I have a piece of code below. When I do a request, I get an invalid grant error. I think that 'id_token' is not valid. But I don't know how to get that id_token, because I get the id_token after the request. Can anybody help me. Big Thanks! headers = { 'alg': 'ES256', 'kid': settings.SOCIAL_AUTH_APPLE_ID_KEY } payload = { 'iss': settings.SOCIAL_AUTH_APPLE_ID_TEAM, 'iat': now, 'exp': now + TOKEN_TTL_SEC, 'aud': 'https://appleid.apple.com', 'sub': settings.SOCIAL_AUTH_APPLE_ID_CLIENT, } client_secret = jwt.encode( payload, settings.SOCIAL_AUTH_APPLE_ID_SECRET, algorithm='ES256', headers=headers ).decode("utf-8") headers = {'content-type': "application/x-www-form-urlencoded"} data = { 'client_id': 'com.scread.app', 'client_secret': client_secret, 'code': 'id_token', 'grant_type': 'authorization_code' } res = requests.post('https://appleid.apple.com/auth/token', data=data, headers=headers) -
Start Uwsgi as low privileged user
I have a server running with Django, uwsgi and nginx. I am unable to start uwsgi as non root user. I did start it as root and it works. I followed the instructions here and here, but I could not locate the socket file at the location specified in the ini (/tmp/blog.sock), nor did changing the rights help. My uwsgi.ini: [uwsgi] # variables projectname = blog base = /var/www/blog # configuration master = true virtualenv = /root/.virtualenvs/blog pythonpath = %(base) chdir = %(base) env = DJANGO_SETTINGS_MODULE=%(projectname).settings.pro module = %(projectname).wsgi:application socket = /tmp/%(projectname).sock chmod-socket = 666 drwxrwxrwx 2 root root 4096 Aug 11 12:37 . drwxrwxrwx 13 root root 4096 Aug 11 09:57 .. -rw-r--r-- 1 root root 643 Aug 11 11:18 nginx.conf -rw-r--r-- 1 root root 535 Aug 11 12:34 nginx.conf.save -rw-r--r-- 1 root root 317 Aug 10 19:40 uwsgi.ini Non root attempt: root@localhost:/var/www/blog# uwsgi --ini config/uwsgi.ini --uid www-data [uWSGI] getting INI configuration from config/uwsgi.ini *** Starting uWSGI 2.0.19.1 (64bit) on [Tue Aug 11 12:29:19 2020] *** compiled with version: 7.5.0 on 10 August 2020 19:38:17 os: Linux-4.15.0-101-generic #102-Ubuntu SMP Mon May 11 10:07:26 UTC 2020 nodename: localhost machine: x86_64 clock source: unix pcre jit disabled detected number of CPU … -
Result backend for Celery in Django with MongoDB
I'm using djongo mongo connector for my Django project. While using django_celery_results for the backend, it throws the exception djongo.sql2mongo.SQLDecodeError: FAILED SQL: UPDATE "django_celery_results_taskresult" SET "date_created" = "django_celery_results_taskresult"."date_done" Any pointers how can I setup celery backend with mongodb? -
Celery change arg parameters and re-run
Suppose that I have some obj, that makes some operation. On failure I want to change attributes of obj and re-run the method class SomeClass: flag = True def do(): if flag: # do something else: # do something different obj = SomeClass() @app.bind(soft_time_limit=7) def do_something(o): o.do() # if everything correct, do nothing, on exception (including timeout) change the flag and rerun o.flag = False o.do() # return result or raise exception if any, no mo retries I'm new to celery and don't know how to do it. I tried to write class-based Task but without any success. The only requirement is that all this should run under one task/process. -
How can a user password be stored in pbkdf2_sha256 format in django?
I am implementing custom register serializer. By the way, the password was encrypted on the admin page, so it was different from the pbkdf2_sha256. like this !eWf3UsvTHU4dJ4F..... I would like to get the user's password using the algorithm of pbkdf2_sha256 instead of this. What should I do? Here's my code. class customRegisterSerializer (serializers.Serializer) : email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED) password = serializers.CharField(required=True, write_only=True) user_Name = serializers.CharField(required=True) profile = serializers.ImageField(use_url=True) def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( _("A user is already registered with this e-mail address.")) return email def validate_password (self, password: str) -> str: return get_adapter().clean_password(password) def get_cleaned_data(self): return { 'email': self.validated_data.get('email', ''), 'password': self.validated_data.get('password', ''), 'userName': self.validated_data.get('userName', ''), 'profile' : self.validated_data.get('profile', ''), } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) return user -
What is application server in python django [duplicate]
Like Java uses Jboss as the application server what application server can be used in case of python django based web application?.. -
Django serving wrong template at the wrong address with malformed urls.py (redactor app)
I’ve got a small experimental Django project which accepts a user’s fake Chuckee Cheese membership card number on the landing page, redacts the first 8 digits and shows it back to the user in redacted form. Here is my website’s landing page showing http://127.0.0.1:8000/: https://i.imgur.com/yHlML9c.jpg When a web user enters their 12 digit card number (for example) ‘111111111111’ into the entry box and clicks the “Redact!” button, Django takes the user to the http://127.0.0.1:8000/home/ location. The redacted card number is present, as expected (below the green font elements): https://i.imgur.com/vGFp5Op.jpg The problem there is that the rest of the content is missing. The redaction functionality works but my intention is for Django to re-serve the same landing page with the redacted card number (rather than taking the user to a separate page). The problem now is either with my app’s views.py, urls.py and template (copied below). I’ve been going back and forth swapping out some variables and replacing them with others but I can’t get it to work. Here is my urls.py: from django.urls import path, include from . import views urlpatterns = [ path('home', views.home, name='home'), # path('results', views.results, name='results'), ] I’ve tried swapping out the first path variable from … -
Table 'avc.consumptions_message' doesn't exist
I'm having a problem and I hope you can help me. When I try to access "message" in the django admin panel y get the next error: Table 'avc.consumptions_message' doesn't exist The thing is that it is true, the table consumptions_message is not in my database. this is my model of Message class Message(LogsMixin, models.Model): """Definición de modelo para Mensajes""" user = models.ForeignKey(User, verbose_name=("Usuario"), on_delete=models.CASCADE) date = models.DateTimeField(("Fecha y hora del mensaje"), default=now) comsumption = models.ForeignKey(Consumption, verbose_name=("Consumo"), on_delete=models.CASCADE) content = models.CharField("Contenido del mensaje", max_length=300, null=False, blank=False) read = models.BooleanField("Leído por el cliente", default=False) deleted = models.BooleanField("Mensaje borrado", null=False, default=False) def __str__(self): string = self.content string = string+"..." return string class Meta: """Meta definición para Mensajes.""" verbose_name = 'Mensaje' verbose_name_plural = 'Mensajes' I have already did "makemigrations" and "migrate" and it doesnt thrown any errors. Any clue guys? -
Django Queryset get all values and first related
I need to get a json response with "customer" fields and the first phone number associated. # models.py class Customer(models.Model): name = models.CharField(max_length=255) surname = models.CharField(max_length=255,) ... class CustomerPhone(models.Model): customer = models.ForeignKey(Customer, related_name = 'phones', on_delete=models.CASCADE) phone_number = PhoneNumberField() ... My customer can have more phone numbers but in summary table I would like to see only the first phone (with min id) When I try with this queryset: Customer.objects.all().values('surname','phones__phone_number') I obtain <QuerySet [{'surname': 'Gates', 'phones__phone_number': '+39123456789'}, {'surname': 'Gates', 'phones__phone_number': '+3998765431'}, {'surname': 'Trump', 'phones__phone_number': '+32123456001'}, {'surname': 'Trump', 'phones__phone_number': '+3298765000'}]> What I can obtain only one result for customer with only one phone number? what can I get -
How to deal with django-subdomains in Django 2.0
Hello everyone I am in the progress of upgrading Django from 1.11 to 2.0. I have run into an issue with the django-subdomains package, where it is attempting to import from django.core.urlresolvers. It looks like this package is no longer maintained. Editing the files in the library is not an option, so I was wondering if anyone had any suggestions for an alternative that I can switch over to relatively easily. -
xhtml2pdf - Set word spacing
Is there any way to set spacing between words in xhtml2pdf besides using &nbsp;? I am trying style="word-spacing: 30px;" but it is probably not supported. -
Django User Profile Update form returning blank
Form is updating without error but after saving form, all fields are empty.Here is my code: #models.py class User(AbstractUser): is_employer = models.BooleanField(default=False) is_jobseeker = models.BooleanField(default=False) class JobseekerProfile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True, related_name='jobseekerprofile') # Basic Information FirstName = models.CharField(max_length=30, blank=False, null=False, verbose_name='First Name') LastName = models.CharField(max_length=30, blank=False, null=False, verbose_name='Last Name') Gender = models.CharField(max_length=20, choices=GENDER_CHOICE) DateOffBorth = models.DateField(verbose_name='Date Of Birth') MarrigeStatus = models.CharField(max_length=20, choices=MARRIED_STATUS_CHOICES, verbose_name='Marrige Status') Religion = models.CharField(max_length=20, choices=RELIGION_CHOOSE) PhoneNumber = models.CharField(max_length=20, verbose_name='Phone Number') Email = models.EmailField(max_length=30, null=False, verbose_name='Email Address') Nationality = models.CharField(max_length=30, choices=NATIONALITY_CHOOSE, verbose_name='Nationality') CurrentAddress = models.CharField(max_length=100, verbose_name='Current Address') PernamentAddress = models.CharField(max_length=100, verbose_name='Pernament Address') ProfileImage = models.ImageField(upload_to = 'Jobseeker/Profile_Pictures', verbose_name='Profile Picture') # Education Information Education = models.CharField(max_length=100, choices=EDUCATION_CHOICES, verbose_name='Education') EducationProgram = models.CharField(max_length=200, verbose_name='Education Program') EducationBoard = models.CharField(max_length=100, choices=EDUCATION_BOARD_CHOICES, verbose_name='Education Board') NameOfInstitute = models.CharField(max_length=200, verbose_name='Name Of Institute') # skill MySkill = models.ManyToManyField(Skill, verbose_name='My Skill') # Past jobs WorkingExperience = models.IntegerField(default=0, verbose_name='Working Experience') WorkedField = models.CharField(max_length=50, null=True, verbose_name='Worked Related Fields') WorkedCompanyName = models.CharField(max_length=200, verbose_name='Worked Company Name') WorkedCompanyWebsite = models.URLField(max_length=200, verbose_name='Worked Company Website') # job category JobCategory = models.ManyToManyField(Category, verbose_name='Job Category') # add language Language = models.CharField(max_length=20, choices=LANGUAGES_CHOICES) # about Me AboutMe = RichTextField(verbose_name='About Me') # Social account Facebook = models.URLField(max_length=100) Twitter = models.URLField(max_length=100) Instagram = models.URLField(max_length=100) # … -
Same data object gets created every-time in django-sqlite3?
I am working on a Django project of scraping some data and storing it in the SQLite database:- models.py file from django.db import models from django.utils.text import slugify class News(models.Model): title = models.CharField(max_length=120) datess = models.CharField(max_length=120) linkss = models.CharField(max_length=120) slug = models.SlugField(blank=True, null=True) def save(self, *args, **kwargs): if not self.slug and self.title: self.slug = slugify(self.title) super(News, self).save(*args, **kwargs) class Meta: verbose_name_plural = "news" def __str__(self): return f'{self.title}' def get_absolute_url(self): return f"/news/{self.slug}" Here's the views.py file from django.shortcuts import render from .models import News from django.core.paginator import Paginator from django.db.models import Q # For scraping part import requests from bs4 import BeautifulSoup def news_list(request, *args, **kwargs): # fOR scraping part - START:::::::::::::::::::::::::::::::::::::::::::::::::::::::: response = requests.get("http://www.iitg.ac.in/home/eventsall/events") soup = BeautifulSoup(response.content,"html.parser") cards = soup.find_all("div", attrs={"class": "newsarea"}) iitg_title = [] iitg_date = [] iitg_link = [] for card in cards[0:6]: iitg_date.append(card.find("div", attrs={"class": "ndate"}).text) iitg_title.append(card.find("div", attrs={"class": "ntitle"}).text.strip()) iitg_link.append(card.find("div", attrs={"class": "ntitle"}).a['href']) # fOR scraping part - END:::::::::::::::::::::::::::::::::::::::::::::::::::::::: # fOR storing the scraped data directly into the dtatbase from the views.py file - START--------------------------------------------------------------- for i in range(len(iitg_title)): News.objects.create(title = iitg_title[i], datess = iitg_date[i], linkss = iitg_link[i]) # fOR storing the scraped data directly into the dtatbase from the views.py file - END----------------------------------------------------------------- queryset = News.objects.all() #Getting all … -
how remove id (path variable ) from viewset in update method(put,patch)?
I want to create a singleton viewset form singleton django model . I need to remove id from path (put /name/{id}/).how remove id from path in djangorestfull viewset put,patch methouds -
Django & Celery unexpected behavior when saving to JSONField
Have celery task started using celery beat with code something like this: class Data(models.Model): data = JSONField(null=True) def store_data(self): data = [] data.append(1) data.append(2) self.data = data self.save() data.append(3) return data I would expected that stored data would be [1, 2] but the reality is [1, 2, 3]. I was trying to find out if celery using atomic or something like this that would explain it but no success. Is this expected behavior? Works fine outside celery. Fix is to use deepcopy like this: ... data_to_save = copy.deepcopy(data) self.data = data_to_save self.save() ... but I would like to know why it doesn't work without it -
Django: update manytomany dropdown menu in form after adding a new register into database
I hope to be clear enough. I have a Campaign model related with a ForeignKey to a Deal model. When I create a new Campaign I have to select the Deal from a dropdown menu and I also have the possibility to create a new Deal pressing the + button. Clicking on this + button opens a new window where you can create and save the Deal. Closing this window and coming back to the 'Create Campaign' one, the new Deal is not displayed in the dropdown menu if not after refreshing the page (which leads to loose all the previous filled fields). How can I replicate the admin behaviour? In the admin pannel after creating the deal the campaign dropdown is automatically updated. My simplified models.py: class campaign(models.Model): Deal = models.ForeignKey(deal, on_delete=models.CASCADE, null=True) Name_Campaign = models.TextField(max_length=50, null=True, blank=True) class deal(models.Model): Deal = models.TextField(max_length=50, null=True, blank=True) My simplified forms.py class create_campaign(ModelForm): Name_Campaign = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "Insert the Campaign Name", "class": "form-control" } )) Deal = forms.ModelChoiceField(queryset=deal.objects.filter(Deal_Type='Father')) class Meta: model = campaign fields = ['Name_Campaign','Deal'] class create_deal(ModelForm): Deal = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "Insert the Deal", "class": "form-control" } )) class Meta: model = deal fields = ['Deal'] My … -
Django runserver
everyone, I have started learning Django and I am unable to run the server python and pycharm are freshly installed I have installed Django by command "pip install Django". After that when I run the command "python manage.py runserver" it gives me error no such file and directory so I copied the manage.py file and paste right under the path which was written and when I typed again it shows me this weird long error I have tried every path but it gives me an error of no such file and directory only on one path which gives me a weird long error which is " (venv) C:\Users\Usman Raees\PycharmProjects\pyshop>python manage.py runserver Traceback (most recent call last): File "C:\Users\Usman Raees\PycharmProjects\pyshop\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Usman Raees\PycharmProjects\pyshop\venv\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\Usman Raees\PycharmProjects\pyshop\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Usman Raees\PycharmProjects\pyshop\venv\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\Usman Raees\PycharmProjects\pyshop\venv\lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ self._setup(name) File "C:\Users\Usman Raees\PycharmProjects\pyshop\venv\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Usman Raees\PycharmProjects\pyshop\venv\lib\site-packages\django\conf\__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\Usman Raees\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", … -
Passing context from Django views to Modal in template
I have the below in my views.py. def IPSEC_ANA(request): results = '' ipsec = IPSEC.objects.all() remote_conn_pre = paramiko.SSHClient() remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) remote_conn_pre.connect(hostname='41.86.xx.xx', port=22, username='root', password='xxxxxxx', look_for_keys=False, allow_agent=False) remote_conn = remote_conn_pre.invoke_shell() remote_conn.send('\n') remote_conn.send('en\n') remote_conn.send(str(password)+ '\n') remote_conn.send('sh run | i access-list ' + acl + '\n') remote_conn.send('\n') time.sleep(1) policy = remote_conn.recv(11111111) time.sleep(1) remote_conn.send('end\n') for line in policy.decode('utf-8').split('\r\n'): if 'access-list ' + acl + ' extended' in line: results = line print (results) context20 = { 'ipsec': ipsec, 'results': results, } template = loader.get_template('ipsecs.html') return HttpResponse(template.render(context20, request)) def ipsecacl(request): if request.method == 'GET': acl = request.GET.get('acl') remote_conn_pre = paramiko.SSHClient() remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) remote_conn_pre.connect(hostname='41.86.xx.xx', port=22, username='root', password='xxxxxxxx', look_for_keys=False, allow_agent=False) remote_conn = remote_conn_pre.invoke_shell() remote_conn.send('\n') remote_conn.send('en\n') remote_conn.send(str(password)+ '\n') remote_conn.send('sh run | i access-list ' + acl + '\n') remote_conn.send('\n') time.sleep(1) policy = remote_conn.recv(11111111) time.sleep(1) remote_conn.send('end\n') for line in policy.decode('utf-8').split('\r\n'): if 'access-list ' + acl + ' extended' in line: results = line print (results) return render(request,{'results': results}, 'ipsecs.html') This is my html: {% extends "layouts/base-site.html" %} {% block content %} <main class="c-main"> <div class="container-fluid"> <div class="fade-in"> <div class="card"> <div class="card-header">Tunnel Info</div> <div class="card w-100"> <div class="card-body"> <table class="table table-responsive-sm table-hover table-outline mb-0"> <thead class="thead-light"> <tr> <th>Tunnel Name</th> <th class="text-center">Tunnel IP</th> <th class="text-center">Tunnel ACL</th> </tr> {% for items in ipsec %} … -
Theory behind changing what django view display based on python script
Hey I want to change image on my webiste based on python script that running in the background and I have no idea how to do it. Script is running continually turning on and off devices and if device is on I want to change what my view display. How do I do it? I have one idea but I dont know if it is good, creating a table in database with boolean values and in my scripts updating a value True/False and in django reading data from database and passing it to view and then using it. Is it good idea? Or there is better option? -
Django: How do I add urlpatterns dynamically for database entries?
The idea is that the admin of the website can upload articles as .html files trough a FileField in the model and it automatically shows up. E.g. file: 'article-Mar-12-2020.html', automatically creates and adds the url "mySite/articles/article-Mar-12-2020.html". How do I add these files to urlpatterns in urls.py?