Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django password format is <algorithm>$<iterations>$<salt>$<hash>, isn't it danger?
when we use django framework usually we use user model when i create_user i need to set password and django always hash my password and when i saw database, password format is <algorithm>$<iterations>$<salt>$<hash> it means if our database was stolen attacker get a salt and how many itered each password. is it okay? i mean... i think i need to hide salt value and iterations value from database thank you :) -
User authentication with Django and NextJS
I am building a project that uses Django Rest Framework as the backend and NextJS serves React frontend. How can I integrate user authentication using these two technologies? In the future we might build a mobile app as well, so we need the backend to be consistent. Thank you for your time. -
django allauth, socialtoken table teardown every time when rerun server
I've found some problem with socialtoken table, every time i got rerun my django server (python manage runserver) data in socialtoken table will be deleted, how can i prevent this action Thanks -
'PaieForm' object has no attribute 'Mois' django
i have one app named prets i create new credit then i print a table of emprunteurs when every emprunteur has a table of months to pay her credit so i want to post the table of every emprunteur models.py class Garantie(models.Model): type = models.CharField(max_length=10) def __str__(self): return self.type class NewCredit(models.Model): """ Garantie = ( (1, 'Chéque'), (2, 'Immobilier'), (3, 'Terrain'), )""" Matricule_emprunteur = models.CharField(max_length=30,null=True) Nom_prénom = models.CharField(max_length=100) Num_compte = models.CharField(max_length=20,null=True) Début_paiement = models.DateField('Date_début_paiement (MM/dd/yyyy)', null=True) Fin_paiement = models.DateField('Date_fin_paiement (MM/dd/yyyy)', null=True) Libellé_garantie = models.ForeignKey(Garantie, on_delete=models.CASCADE) Valeur_garantie = models.CharField(max_length=30,null=True) Montant = models.CharField(max_length=30,null=True) Taux_interet = models.CharField(max_length=30,null=True) Interet_rem = models.CharField(max_length=30,null=True) Total_rem = models.CharField(max_length=30,null=True) def __str__(self): return self.Matricule_emprunteur class PaieCredit(models.Model): emprunteur= models.OneToOneField(NewCredit, on_delete=models.CASCADE, primary_key=True,default='0') Mois = models.CharField(max_length=50) Archiver = models.BooleanField(default=False) def __str__(self): return self.Matricule_emprunteur forms.py class CreditForm(forms.ModelForm): class Meta: model = NewCredit fields = '__all__' def __init__(self, *args, **kwargs): super(CreditForm,self).__init__(*args, **kwargs) self.fields['Libellé_garantie'].empty_label = "Select" class PaieForm(forms.ModelForm): class Meta: model = PaieCredit fields = '__all__' views.py def Emprunteurs_detail(request, id=0, emprunteur_id=0): if request.method == "GET": if id == 0: form = CreditForm() frm = PaieForm() else: emprunteur = NewCredit.objects.get(pk=id) form = CreditForm(instance=emprunteur) result = [] debut = emprunteur.Début_paiement fin = emprunteur.Fin_paiement while debut <= fin: result.append(debut) debut += relativedelta(months=1) list_month = [] for x in result: … -
How to speed up reading and writing binary file operation in python?
I have got a binary file(400MB) that I first want to read and then write to another file in python.Currently what I'm doing is very basic. file = 'file.bin' with open('temp','wb+') as dest: for chunk in file.chunks(): dest.write(chunk) This code is a part of my Django app that I want to speed up.Is there any other better way to speed up this operation? -
Django - Management Command - Pandas read_csv - Localhost working - Heroku
I seem to come across unique situations throughout this month. I need to read a file from the web and update the database. I have taken two approaches : Approach 1. Upload the values from the application itself - this could be time consuming and I could hit worker timeout - however, I have retained this approach - as it currently takes 27-29 seconds. Heroku timeout is at 30 seconds. Approach 2. Upload the values from Django Command Management . I have scheduled a job via Heroku. I used pandas - pd.read_csv file for reading a file from the web. Scenario 1: If I use approach 1, Localhost : It works fine Heroku : It works fine Scenario 2 : If I use approach 2, Localhost : It works fine Heroku : HTTP 503 error and not able to read the file What could be the solution for this ? P.S. - I plan to put requests and add a browser header and update this thread. -
RabbitMQ for http/https request queuing in Django
One of my clients wants to use RabbitMQ for request queuing on his Django DRF powered web app. the app is simple just saving and listing information with attachments (over S3 storage) with high traffic. As I know RabbitMQ acts as message broker which can be helpful while doing long tasks/sending emails/ generating PDFs. I am curious to know that in my scenario can I use rabbitMQ? and if yes then what will be the advantages of using it. -
raise ImproperlyConfigured("Error loading psycopg2 module: %s" django.core.exceptions.ImproperlyConfigured:
**I AM NEW TO DJANGO . WHEN I TYPE python manage.py makemigrations I GOT THE FOLLOWING ERROR** PS C:\Users\Aman\employee_project> python manage.py makemigrations Traceback (most recent call last): File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\postgresql\base.py", line 25, in <module> import psycopg2 as Database File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\psycopg2\__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Aman\employee_project\manage.py", line 21, in <module> main() File "C:\Users\Aman\employee_project\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File … -
Django notification whenever interrupt happens
I have a django application which is integrated with c++ using subprocess. I need to show notifications whenever interrupt happens, For eg. if camera have any issues like reconnecting,not found etc, if the django part has any issues ... My django app needs to notify as well as it has to send request to corresponding part to solve the issue Could I use signal of django for this purpose? Is there any other way for solve this? -
How do I use python reverse() function to pass list of ids as query parameter?
I need to generate a URL with a list of object ids as query params. i.e Url will look something like admin/app/model/?id__in=1,2,3. I have used reverse('admin:app_model_changelist', kwargs={id__in:<list_of_ids>}) which doesn't seem to work -
Geeting Error "django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: NO)")"
i am providing correct credentials still getting this error. as i can access my MYSQL through writting simple python program with same credentials but i could access MYSQL through Django... need help i am attaching my screen capture of error enter image description here enter image description hereI.png -
Forgot to delete model objects before altering model fields in models.py
I am getting this error continuously when I try to open this database through django admin Exception Type: OperationalError at /admin/tasks/task/ Exception Value: no such column: tasks_task.task_name_id Initially I changed a lot a fields in models which already had some objects stored. Now I couldnt have gone back so i started a new app and copied all the files from old app as they were in the same project. deleted the old app and renamed the new app by the name of old one so that in the project wherever refrenced there wont be any problem. but now whenever i try to migrate i get this error: File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py", line 326, in check_constraints raise utils.IntegrityError( django.db.utils.IntegrityError: The row in table 'tasks_task' with primary key '1' has an invalid foreign key: tasks_task.task_name_id cont ains a value 'task_name_id' that does not have a corresponding value in tasks_task_list.id. models.py: from django.db import models import datetime from django.utils import timezone class Task_List(models.Model): task_name=models.CharField(max_length=100) c1=models.CharField(max_length=30, default="OTHER") c2=models.CharField(max_length=30, default="OTHER") c3=models.CharField(max_length=30, default="OTHER") time_esc=models.IntegerField(default=1) def __str__(self): return self.task_name class Task_manager(models.Manager): def create_Task(self, title,deadline): Task1 = self.create(title=title,deadline=deadline) # do something with the book return Task1 class Task(models.Model): STATUS = ( ('ONGOING', 'ONGOING'), ('COMPLETED','COMPLETED'), ('PENDING','PENDING' ), ('FINISHED','FINISHED') ) task_name=models.ForeignKey(Task_List, on_delete=models.SET_NULL, … -
make request to django URL's app from celery task
I have a django rest framework application which uses caching for some of the URLS. I am using cache_page decorator for caching these URL's in redis cache. These caches expire after 5 min. Now I want to implemnt a celery task that is called periodically (using celerybeat) after every 30 seconds to check if the cache for a particluar page exists or not in the redis cache. If not we need to create a cache. The problem here is that I don not have the request and response object since it is a celery task. I need a way to make request to the django application which will then perform the caching automatically. what should be the best approach for this ? -
Update m2m,foreignkey field to model does not work in DRF
Update to the following News model does not work in DRF.( address is not updated) The creation works fine. class News (models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=20) text = models.TextField() group_address = models.ManyToManyField(Group, blank=True) user_address = models.ForeignKey(User, on_delete=models.CASCADE) class Group(models.Model): id = models.AutoField(primary_key=True) group_name = models.CharField(max_length=20) class User(models.Model): id = models.AutoField(primary_key=True) user_name = models.CharField(max_length=20) class NewsSerializerViewSet(viewsets.ModelViewSet): queryset = News.objects.all() serializer_class = NewsSerializer class NewsSerializer(serializers.ModelSerializer): class Meta: model = News fields = '__all__' -
Autocomplete issue to html codes in django project in visual studio code
I have no problem with python codes in visual studio code even js codes autocomplete is working when im doing django project but when i try to type html codes in .html files,there is a autocomplete problem. Some codes autocompletes are working,the codes from django like {% block %} {% endblock %} but the pure html codes like etc. i cannot get any hint from the extensions.Btw i got many snippets which is related html js python django etc. only problem with the html codes. How can i solve the issue.. thanks in advance.. https://i.stack.imgur.com/9h3oc.png -
How can i send reminder message to customer before 2 hours in django/python
I am developing a web app for online ticket buying. I used telesign API to integrate sms system. Now i want a reminder system for my web app, it should send sms to customer before 2 hours of start time of movie. -
Django get data from form submission
I had something that I'm missing because I already worked with databases and forms.py, but when it comes to get the data from a simple form, it never work for me: I tried the below, and it's not printing anything when I'm searching - Thanks! Any recommendations for fixing it, or handling filtering in a better way will be appreciated. Urls.py app_name = 'adolim' urlpatterns = [ path('', views.home, name='home'), path('clients/', views.clients_view, name='clients'), path('clients/', views.clients_filter_view, name='filter_clients'), clients.html <form action="{% url 'adolim:filter_clients' %}" method="post" > {% csrf_token %} <div class="input-field col s3"> <input name="phone_number" id="phone_number" type="text" class="validate"> <label for="phone_number">לפי מספר טלפון</label> </div> <div class="input-field col s3"> <input name="first_name" id="first_name" type="text" class="validate"> <label for="first_name">לפי שם פרטי</label> </div> <div class="row left"> <button class="btn waves-effect waves-light blue" type="submit" name="action">חפש לקוח <i class="material-icons right">search</i> </button> </div> </form> Views.py def clients_filter_view(request): first_name = request.POST.get('first_name') phone_number = request.POST.get('phone_number') print(first_name, phone_number) return render(request, 'adolim/clients.html', data_to_render) -
How to deploy files to django application without affecting the cron function?
We have different cron functions that are being executed in various hours of the day. When it comes to any file deployment the cron function gets affected. Those cron functions affect certain functions in different files during deployment the cron is broken and fails. We are using AWS code deploy service. how to overcome this situation? -
Django role based form
I have two users a customer and an admin. And I have an update and a create form with a status field and other fields. The status filed displays whether the order is received, scheduled, or in manufacturing. I want only the admin to update that field and customer to only view it. Can anyone tell me how can I implement it? Thanks! -
Hosting Django+PostgreSQL to server
I am not familiar with databases, I tried connecting Django+PostgreSQL. During hosting the Django app to cloud, should I install PostgreSQL to server space ? I have experience in hosting Django with default SQLite, I did not have to think about database as its default with Django. I am using www.pythonanywhere.com as hosting provider and it support PostgreSQL. -
Django - How user authentication is different than session authentication
I am new to django trying to write some apis. Django has user based authentication request.user.is_authenticated() to check whether a valid user is logged in or not. There is also session authentication. 1. How session authentication is different than django user based authentication? 2. Which is more secure? I am trying to write rest apis that calls third party apis. 3.Is it posssible to use tastypie SessionAuthentication without using model? I didn't find any rest api example that has implemented tastypie without model. -
image embedded in email HTML template - Flask-mail ValueError: too many values to unpack (expected 2)
I tried to send a response email from HTML template that include an image on header. If I send HTML without image attachment there is not error but it is a text email like. I searched and test for couple of days, no success. Flask-email snippet is msg = Message(form.title.data, recipients=['emial@gmail.com']) msg.html = render_template('mail_temp/file.html') with open('/home/daniel/PycharmProjects/Sitio/blue/static/pictures/ribbon.jpg', 'rb') as fp: msg.attach('ribbon.jpg', 'image/jpg', fp.read(), 'inline', headers={'Content-ID': 'ribbon'}) mail.send(msg) HTML template include image in: <td> <img src="cid:ribbon"/> </td> The issue seems happen in the parameter for Message.Attach method. I found a similar question and response but 2 years old, maybe the method changes it. Thanks in advance. File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/daniel/PycharmProjects/Sitio/blue/site/routes.py", line 220, in contactme mail.send(msg) File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask_mail.py", line 492, in send message.send(connection) File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask_mail.py", line 427, in send connection.send(self) File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask_mail.py", line 190, in send message.as_bytes() if PY3 else message.as_string(), File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask_mail.py", line 385, in as_bytes return self._message().as_bytes() File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask_mail.py", line 371, in _message for key, value in attachment.headers: ValueError: too many values to unpack (expected 2) `` -
Assigning a group of models to another model
I'm creating a task completion app where a user can create a project, then users can create tickets for that specific project. The problem is that when I create a foreignkey object, it requires a default value. There are no projects right now to set as default. Here are my models class Projects(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=140) class Post(models.Model): LOW = 1 NORMAL = 2 HIGH = 3 STATUS_CHOICES = [ (LOW , 'Low'), (NORMAL, 'Normal'), (HIGH, 'High'), ] TYPE_CHOICES = [ ('Features', 'Feature Request'), ('Bug/Error', 'Bug/Error'), ('Design', 'Design'), ] PROGRESS_STATUS = [ ('Open', 'Open'), ('InProgress', 'In Progress'), ('AddInfo', 'Additional Info Required'), ('Completed', 'Completed'), ] #all_users = Profile.objects.all() #all_user_choices = ((x.user, x.user) for x in all_users) title = models.CharField(max_length=50) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) priority = models.IntegerField( choices=STATUS_CHOICES) status = models.CharField(choices=PROGRESS_STATUS, default='Open', max_length=25) ticket_type = models.CharField(choices=TYPE_CHOICES, default ='Features', max_length=25) project = models.ForeignKey(Projects, on_delete=models.CASCADE) #assigned_developer = models.CharField(choices=all_user_choices, default=author, max_length=50) Thanks! -
JavaScript preventing form submission
I'm working on a Django project and one of the forms won't submit. I figured out that the culprit is some JavaScript that formats the currency input (when I remove the JS or remove the input type="currency", it submits) This is my simplified form: <form action="{% url 'create_goal' %}" method="post"> {% csrf_token %} <h4 class="mb-3" id="create">Create a Savings Goal</h4> <input type="text" class="form-control" id="goalName" name="goalName" value="" required> <input type="currency" min="0" pattern="^\d*(\.\d{0,2})?$" class="form-control" id="goal" name="goal" required> <button type="submit" class="btn btn-secondary btn-block">Add Goal</button> </form> {% load static %} <script src="{% static 'starling/currency.js' %}"></script> This is the JavaScript (I got it from here: html5 input for money/currency): var currencyInput = document.querySelector('input[type="currency"]') var currency = 'GBP' // format inital value onBlur({target:currencyInput}) // bind event listeners currencyInput.addEventListener('focus', onFocus) currencyInput.addEventListener('blur', onBlur) function localStringToNumber( s ){ return Number(String(s).replace(/[^0-9.-]+/g,"")) } function onFocus(e){ var value = e.target.value; e.target.value = value ? localStringToNumber(value) : '' } function onBlur(e){ var value = e.target.value var options = { maximumFractionDigits : 2, currency : currency, style : "currency", currencyDisplay : "symbol" } e.target.value = value ? localStringToNumber(value).toLocaleString(undefined, options) : '' } -
How to use inlineformset_factory when multiple Foreign key
I have four models of the shop, customer, product, an order. I am showing the relation of models shop user = models.OneToOneField(User, null=True, related_name='shop', blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=70, null=True, default='shop', ) address = models.CharField(max_length=70, null=True) Shop_category = models.CharField(max_length=200, null=True, ) customer user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, default='customer') Phone = models.PositiveIntegerField(blank=True, null=True) product shop = models.ForeignKey(Shop, models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, blank=True) Brand = models.CharField(max_length=200, blank=True) description = models.TextField(null=True, blank=True) order shop = models.ForeignKey(Shop, models.CASCADE, null=True) customer = models.ForeignKey(Customer, models.CASCADE, null=True) product = models.ForeignKey(Product, models.CASCADE, null=True) quantity = models.CharField(max_length=30) date_created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=200, choices=STATUS, default='Pending') note = models.CharField(max_length=1000, null=True) when customers login then the shop will print on the screen and a button on shop to show the products by the shop in the form card. On the product card, there is an order button that adds the product in order after submitting the selected product will print with the remaining filled of order that show in the image how I can create an order so that the customer in order is the instance and the shop in order is that shop which is selected to show the products, and products which are …