Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to create user in auth_user in Django but I am getting this error TypeError at /register/ set_password() missing 1 required
Hello I am trying to create user in auth_user in database but it is showing me a error The method I am using from django.contrib.auth.models import User user = Users.objects.get(username='myuser') user.set_password('mypassword') user.save() My views.py def registerpage(request): if request.method == 'POST': myusername = request.POST['name'] email = request.POST['email'] pass1 = request.POST['password1'] pass2 = request.POST['password2'] myuser = User.objects.get(username=myusername) User.set_password('pass1') myuser.name = myusername myuser.email = email myuser.password = pass1 myuser.save() return redirect('testlogin') The error that I am getting TypeError at /register/ set_password() missing 1 required positional argument: 'raw_password' I need help ! -
django models cyclic import
I have read some relevant posts on the issue on mutual imports (circular). I am working on a django app, here's how I run to an issue: I have two apps, first one articles, second one tags my article model have a many to many field, to indicate relevant tags: articles/models.py from django.db import models from tags.models import Tag class Article(models.Model): tags = models.ManyToManyField(Tag) however, in my tags app, I also need to import Article model to achieve the methods: tags/models.py from django.db import models from articles.models import Article # Create your models here. class Tag(models.Model): title = models.CharField(max_length=100) content = models.CharField(max_length=255) def getAritcleLength(): pass def getQuestionLength(): pass I usually use a module to combine those class definitions, normally won't run into issue according to method resolution order. However, in django the workflow we need to put classes into separated folders, I will be so glad for any suggestion. -
Access and modify Django DB without login in as superuser
I have a newbie question here. I'm currently working on a site where the user can add items to a model I created. The thing works fine if I'm logged in as super admin in the Django admin panel, but if I'm not, the CSRF verification doesn't work and I can't operate. Is this a "Debug: True" thing? Once I'm ready to production and turn debug off, will it work without login? Thanks! -
How to execute django runserver and python script at the same time (on one line in cmd)
I have wrote a python script which automatically uploads files from a given folder to a django modell. I want this script running while django server is running. My script runs perfectly when I run it in pycharm console. I have tried a few command to achieve this: python manage.py runserver & python manage.py shell < myscript.py python manage.py runserver & python manage.py runscript -v3 myscript In the first case nothing happens until I press ctrl+c, then it display errors "unexpected indent" for every single row of my code. In the second case my script starts to run only when I press ctrl+c (so my django server is shut down and my script is executed). I am using windows so celery is not a good alternative for me (and celery is overkill for such a simple task like that). -
when i use "recognizer = cv2.face.LBPHFaceRecognizer_create()" in normal program it run but when i used it in Django it gives me mudule error
I am doing my acdemic project i am using face recogangnation in python using opencv LBPH algorithm. It works fine when i used in normal program. But when i use that same function in django it gives me module not found error. this function work finr with noraml execution ''' def result(): video = cv2.VideoCapture(0) correct_result = [] BASE_DIR = Path(__file__).resolve().parent # Give The base path = D:\BE\Final Project\Hostel_Automation\Face model_path = (str(BASE_DIR)+ "/static/models/trained_model2.yml").replace(os.sep,'/') # Give the path of model = D:/BE/Final Project/Hostel_Automation/Face/static/models/trained_model2.yml recognizer = cv2.face.LBPHFaceRecognizer_create() # creates an instance for 'LBPHFaceRecognize' Recognizer recognizer.read(model_path) count = 0 # video = cv2.VideoCapture(0) # 0 means system camera for other external camera use 1 while 1: check, frame = video.read() # check parameter gives true value if camera is is correctly configure if check: gray_img = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) face = face_classifire.detectMultiScale(gray_img, scaleFactor=1.2, minNeighbors=5) if face is (): print("face not found") else: count += 1 for(x,y,w,h) in face: ID , conf = recognizer.predict(gray_img[y:y+h,x:x+w]) confidence = int(100*(1-(conf)/300)) if confidence >75: print("founded" , ID) correct_result.append(ID) cv2.putText(frame , "Founded " + str(confidence), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0),2) else: print("not founded") cv2.putText(frame, "Unknown" + str(confidence), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 128, 0),2) cv2.imshow('im', frame) cv2.waitKey(2) else: print("please … -
Filtering Model Fields with button in Django
i'll include my code first Models: Base.html: (for the navbar button) views.py: and this is the page: So what i want to do is if the user click the button, the page is filtering and just return the book with requested genre. Is it possible if not using jquery,ajax, etc?, if not it's ok but give me an explanation. -
How can I display different fields for staff and superuser in django admin page
I am developing a django website where I want to super user to be able to create posts with the name of other users but don't want the staff members to be able to do it. so I want the field user to be displayed only to the super user and not to the staff. -
I need a django way of query for my need. Help me with it. I am new to Django
I need a Django way of query. Now I am using raw query. Which is not very useful. SELECT parent.id CASE WHEN child.subject is NULL THEN parent.subject ELSE child.subject END as subject FROM parent LEFT JOIN child on parent.id=child.id Please help me with it. -
problems dropdown filter saving data in the database
I have a problem with a select that filters the other. I did all the filtering correctly from the frontend point of view but in the backend I can not save the data. This is the error: select a valid choise. That choice is not one of the available choices. I think the problem is in the fact of the form as it does not find 'group_single' that I pass through post in my views. my models class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente' ) class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField( choices = giorni_settimana_scelta, default = '-' ) dati_gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'dati_gruppo' ) gruppi_scheda = models.ForeignKey( Schede, on_delete = models.CASCADE, related_name = 'gruppi_scheda' ) class DatiEsercizi(models.Model): serie = models.IntegerField() ripetizione = models.IntegerField() peso = models.DecimalField( max_digits = 4, decimal_places = 1, blank = True, null = True ) dati_esercizio = models.ForeignKey( Esercizi, on_delete = models.CASCADE, related_name = 'dati_esercizio' ) … -
Django create spesific Queryset
I want to find the ones whose price is 100 dollars in CompanyProduct and get their Product queries.(queryset format) Product Model: product_name = models.CharField(max_length=300, verbose_name="Product Name") slug = models.SlugField(unique=True, editable=False, max_length=300) category = models.ForeignKey('ProductCategory', null=False, on_delete=models.CASCADE, max_length=100, verbose_name="Category") brand = models.ManyToManyField('Brand', null=True, max_length=100, verbose_name="Brand") CompanyProduct Model: product = models.ForeignKey('product.Product', on_delete=models.CASCADE, verbose_name="Product") company = models.ForeignKey('company.Company', on_delete=models.CASCADE, verbose_name="Company") price = models.IntegerField(blank=True, null=True, verbose_name="Price") -
How can I edit or customize the required characters of a username field?
I'm making a blog type website, and it's pretty much done but earlier today I realized a major flaw in it. When creating creating a username (when registering or editing one's profile) it asks for certain characters, but it won't allow me to have spaces in my name. For example if I wanted my username to be "Winston Pichardo", it won't be possible because that will trigger the error that says "only letters and digits as @/./+/-/_ are allowed". So how can I edit these 'requirements' to allow spaces in the username? I'm using the default django forms and combining those with Crispy Forms to make it all work. these are some examples of my code: forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField( label= 'Correo Electrónico', required=True, ) username = forms.CharField( label = 'Nombre de Usuario', required=True, ) password1 = forms.CharField( label = "Contraseña", required=True ) password2 = forms.CharField( label = "Confirmar Contraseña", required=True ) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField( label='Correo Electrónico', required=True ) username = forms.CharField( required=True, label='Nombre de Usuario' ) class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): image = forms.ImageField( label = 'Foto de … -
Is there a built-in way to set a maximum relations size for ManyToManyField?
Initially I had an ArrayField that could have a maximum of 3 enums inside it. But with my project getting more complex, I had to change this field to a separate model, which has other fields along (but the enum still the same). The target model, which previously contained the ArrayField would then need a ManyToMany in order to correctly reference these multiple instances, with a limit of 3 instances max. I know I could override the save method in order to check this before saving, but I was curious if there's a built-in way in the MTM field to do this kind of check -
Unable to integrate a database (with images) into a Django project
I am trying integrate a database full of questions (with images) into a sqlite3 database in Django. After running 'inspectdb', I pushed the model at the appropriate place. My model looks like this: class Questions(models.Model): main_ques = models.IntegerField(db_column='Main_ques', blank=True, null=True) sub_ques = models.TextField(db_column='Sub_ques', blank=True, null=True) page_num = models.IntegerField(db_column='Page_num', blank=True, null=True) marks = models.IntegerField(blank=True, null=True) topic = models.TextField(db_column='Topic', blank=True, null=True) subques_images = models.ImageField(db_column='Subques_images', blank=True, null=True) mainques_image = models.ImageField(blank=True, null=True) class Meta: managed = True db_table = 'questions' And my 0001_initial.py looks like this: class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Questions', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('main_ques', models.IntegerField(blank=True, db_column='Main_ques', null=True)), ('sub_ques', models.TextField(blank=True, db_column='Sub_ques', null=True)), ('page_num', models.IntegerField(blank=True, db_column='Page_num', null=True)), ('marks', models.IntegerField(blank=True, null=True)), ('topic', models.TextField(blank=True, db_column='Topic', null=True)), ('subques_images', models.ImageField(blank=True, db_column='Subques_images', null=True, upload_to='')), ('mainques_image', models.ImageField(blank=True, null=True, upload_to='')), ], options={ 'db_table': 'questions', 'managed': True, }, ), ] The admin page looks like this.. But after that it says, this Error message I get I am pasting the error message below: OperationalError at /admin/sql_inte/questions/ no such column: questions.id Request Method: GET Request URL: http://127.0.0.1:8000/admin/sql_inte/questions/ Django Version: 3.2.8 Exception Type: OperationalError Exception Value: no such column: questions.id Exception Location: /Users/BivashChakraborty/PycharmProjects/database/venv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py, line 423, in execute Python Executable: /Users/BivashChakraborty/PycharmProjects/database/venv/bin/python Python Version: 3.7.0 … -
ModuleNotFoundError: No module named 'backend'
Running "python manage.py collectstatic" for a Django app I hope to host on Heroku results in this error: Traceback (most recent call last): File "C:\Code\Django\store\manage.py", line 22, in <module> main() File "C:\Code\Django\store\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 161, in handle if self.is_local_storage() and self.storage.location: File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 215, in is_local_storage return isinstance(self.storage, FileSystemStorage) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 246, in inner self._setup() File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\staticfiles\storage.py", line 438, in _setup self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)() File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\files\storage.py", line 366, in get_storage_class return import_string(import_path or settings.DEFAULT_FILE_STORAGE) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'backend' I tried following that path and saw that there was no python file … -
Django ORM: group query results by day
I has next Model: class Invoice(AbstractOrder): order = models.ForeignKey(Order, related_name="invoices",...) is_paid = models.BooleanField() paid = models.DecimalField() paid_at = models.DateField() tax = models.IntegerField() total = models.IntegerField() date = models.DateField() number = models.CharField() client_accepted_at = models.DateTimeField() issued_at = models.DateTimeField() prepared_at = models.DateTimeField() Based on this model I render PDF`s with query, filtered by 'from_date' and 'to_date'. Query looks like this: invoices = Invoice.objects.filter(date__gte=date_gte, date__lte=date_lte) This query return me list of Invoices like But I need to group this resulpt by each date like next and count invoices per day, all items in all invoices at this day, same as taxs, totals, etc: -
Django How to get the value from many to many relationship
I have a product update form where I want to update the sizes of a product, with a many-to-many column relation. I am able to get the saved values but I can't get item ID or size. {{item.id}} shows empty value. {% for item in form.size.value %} <span> <input type="checkbox" name="size" id="{{ item.id }}" value="{{ item.id }}"> <label for="{{ item.id }}">{{ item }}</label> </span> {% endfor %} SIZE MODEL class Size(models.Model): identifier = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) size = models.CharField(max_length=200, unique=True, null=False, blank=False) active = models.BooleanField(default=True) date_created = models.TimeField(verbose_name='Date Created', auto_now_add=True) date_updated = models.DateTimeField(verbose_name='Last Updated', auto_now=True) PRODUCT MODEL class Product(models.Model): identifier = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=200, null=False, blank=False) slug = models.SlugField(max_length=30, unique=True) showcased = models.BooleanField(default=False) recommended = models.BooleanField(default=False) active = models.BooleanField(default=True) price = models.DecimalField(max_digits = 5, decimal_places = 2, null=True, blank=True) pagetitle = models.CharField(max_length=200, null=True, blank=True) shortDescription = models.CharField(max_length=200, null=True, blank=True) longDescription = HTMLField(null=True, blank=True) specifications = models.TextField(null=True, blank=True) features = models.TextField(null=True, blank=True) care = models.TextField(null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.PROTECT) subCategory = models.ForeignKey(SubCategory, null=True, blank=True, on_delete=models.PROTECT) image = models.ManyToManyField(Image, blank=True) size = models.ManyToManyField(Size, blank=True) tag = models.ManyToManyField(Tag, blank=True) date_created = models.TimeField(verbose_name='Date Created', auto_now_add=True) date_updated = models.DateTimeField(verbose_name='Last Updated', auto_now=True) I have tried different ways but not had success in … -
Django setlang view does not exist - what could be the problem?
I want to create a button to choose between two languages, but when I'm clicking on it I am encountering error saying that view does not exist, what could be the problem? Error: DatabaseError at /en/i18n/setlang/ ORA-00942: table or view does not exist Template: {% get_current_language as LANG %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <form action="{% url '/i18n/' %}" method="post" id="form_{{ language.code }}" style="display:inline!important;"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <input name="language" type="hidden" value="{{ language.code }}" /> </form> <button class="lang-button" type="submit" form="form_{{ language.code }}" value="Submit">[{{ language.code }}]</button> {% endfor %} URLS: urlpatterns = [ # url(r'', include('label_uwm.urls')), ] urlpatterns += i18n_patterns( url(r'', include('label_uwm.urls')), url(r'i18n/', include('django.conf.urls.i18n')), ) SETTINGS: LANGUAGE_CODE = 'pl' LANGUAGES = ( ('pl', _('Polish')), ('en', _('English')), ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.i18n', ) MIDDLEWARE = ( 'django.middleware.locale.LocaleMiddleware', [...]) -
No module named 'imagekit' in django rest framework
i'm running into a very weird error in django rest framework. I tried all the solutions proposed in stackoverflow but nothing. the error: Traceback (most recent call last): File "C:\Users\User\Desktop\IVAN.ru\IVAN_backend\backend\manage.py", line 22, in <module> main() File "C:\Users\User\Desktop\IVAN.ru\IVAN_backend\backend\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\User\Desktop\IVAN.ru\IVAN_backend\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\User\Desktop\IVAN.ru\IVAN_backend\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\User\Desktop\IVAN.ru\IVAN_backend\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\Desktop\IVAN.ru\IVAN_backend\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\User\Desktop\IVAN.ru\IVAN_backend\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\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 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'imagekit' please notice that i added 'imagekit' to installed apps , I uninstalled and reinstalled everything. but nothing worked for me. I installed django-imagekit and uninstalled Imagekit. i tried to replace 'imagekit' with 'Imagekit' . -
Django FormField: How to set `max_length` and other properties in a baseclass
I'd like to set label and max_length inside IBANField to generalize it and use it somewhere else. validate_iban is a validator function. Here is what I have now. It's ok, but not what I want. class IBANField(CharField): default_validators = [validate_iban] class SepaForm(forms.Form): iban = IBANField(max_length=34, label=_('IBAN')) -
Migration from bootstrap, django to react
I have a whole website build with frontend using bootstrap and backend with django and now i want to migrate the project to react as frontend by reusing as much as code possible. As i am new to react i am having a hard time to migrate the project. can anyone share some resources are sugestions. I am attaching my index.html for your reference. {% extends 'lab/navbar.html' %} {% load static %} {% block content%} <style> #newhr { border: 0; height: 1px; background-image: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0)); } #button { background-color: #1c87c9; border: none; color: white; padding: 20px 34px; text-align: center; text-decoration: none; display: inline-block; font-size: 20px; margin: 4px 2px; cursor: pointer; } </style> </head> <body> <!-- START carousel--> <div class="container"> <div class="carousel slide" id="main-carousel" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#main-carousel" data-slide-to="0" class="active"></li> <li data-target="#main-carousel" data-slide-to="1"></li> <li data-target="#main-carousel" data-slide-to="2"></li> <!--<li data-target="#main-carousel" data-slide-to="3"></li>--> </ol><!-- /.carousel-indicators --> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block img-fluid" src="{% static 'lab\images\carousel_photos\Figure_Transl-Bioinfo_home.jpg' %}" alt=""> <div class="carousel-caption d-none d-md-block"> <h3 style="color: white;">Biomaterial</h3> <p>We develop innovative biomaterials that can be used to <br> treat injuries or replace damaged tissues.</p> </div> </div> <div class="carousel-item"> <img class="d-block img-fluid" src="{% static 'lab\images\carousel_photos\dna.jpg' … -
Django-Q does not kill old threads and CPU raises 100%
I'm deploying Django-Q on a production server using a systemd service like below: [Unit] Description=Django-q management service After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/api $e/ubuntu/.virtualenvs/env/bin/python manage.py qcluster Restart=always [Install] WantedBy=multi-user.target Every time qcluster starts a thread (about 8.5% CPU), the old ones does not die and CPU raises 100%. PD: The problem is also happening if I run qcluster directly on the terminal. -
What data format is this in google gantt chart? How can I return a format like this in Django?
I'm trying to integrate the google Gantt chart into my Django project, there's a model for tasks, the model has 2 date fields already, one is a start date and another is the due date. I tried to understand the data format the google chart requires, it was like ['Research', 'Find sources', new Date(2015, 0, 1), new Date(2015, 0, 5), null, 100, null], I'm confused, how could a month be 0, and the format seems like a list, how can I output a format like this in Django, I tried to google it, it seems like not many people using google chart and even less in the Gantt chart, I think it's a JSON format, but I have very limited knowledge of how to deal with JSON, does anyone have any idea about how to return the data format to HTML? Cheers chart.html ''' <script type="text/javascript"> google.charts.load('current', {'packages':['gantt']}); google.charts.setOnLoadCallback(drawChart); function daysToMilliseconds(days) { return days * 24 * 60 * 60 * 1000; } function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Task ID'); data.addColumn('string', 'Task Name'); data.addColumn('date', 'Start Date'); data.addColumn('date', 'End Date'); data.addColumn('number', 'Duration'); data.addColumn('number', 'Percent Complete'); data.addColumn('string', 'Dependencies'); data.addRows([ ['Research', 'Find sources', new Date(2015, 0, 1), new Date(2015, … -
How to pass an object to a model field in Django?
I am trying to pass an object I get from a model form to a field in a model. Three models are involved here. Patient , Donation and Donor Here are the models: class Donor(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) donor_dob = models.DateField(auto_now=False, auto_now_add=False, default=None) id_card = models.CharField(max_length=7) phone_number = models.CharField(max_length=7) blood_group = models.CharField(max_length=20, choices=BLOOD_GROUPS, default='O_Positive') availability = models.BooleanField(default=True) donor_donation = models.ForeignKey( 'Donation', blank=True, null=True, on_delete=models.DO_NOTHING) class Patient(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=30) patient_dob = models.DateField(auto_now=False, auto_now_add=False, default=None) id_card = models.CharField(max_length=7) phone_number = models.CharField(max_length=7) blood_group = models.CharField(max_length=20, choices=BLOOD_GROUPS, default='O+') class Donation(models.Model): donation_donor = models.ForeignKey( Donor, on_delete=models.CASCADE, related_name='donations') patient = models.ForeignKey(Patient, on_delete=models.CASCADE) donation_date = models.DateTimeField(auto_now=True) amount = models.DecimalField(max_digits=5, decimal_places=2) I am using DonationForm to enter a new donation record. here is the form: class DonationForm(forms.ModelForm): donation_donor = forms.ModelChoiceField( queryset=Donor.objects.filter(availability=True)) class Meta: model = Donation fields = ['donation_donor', 'patient', 'amount'] and finally here is the view for entering a new donation object/record def new_donation(request): if request.method == 'POST': form = DonationForm(request.POST or None) # print(request.POST) print(request.POST['donation_donor']) if form.is_valid(): donor = Donor.objects.get(id=request.POST['donation_donor']) donor.availability = False print('Donor: ', donor) donation = form.save() form.save() donor.donation_donor = donation donor.save() donor = setattr(donor, 'donation_donor', donation) print(donor) return render(request, 'new_donation.html', {'form': form}) form = DonationForm() return … -
Django psycopg2.errors.InvalidSchemaName: no schema has been selected to create in
I am trying to configure PostgreSQL in my Django project with a custom schema. My settings are: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['DB_DATABASE'], 'USER': os.environ['DB_USERNAME'], 'PASSWORD': os.environ['DB_PASSWORD'], 'HOST': os.environ.get('DB_HOST', 'localhost'), 'PORT': os.environ.get('DB_PORT', '5432'), 'OPTIONS': { 'options': '-c search_path=my_custom_schema', }, } } I want django system tables to be created in the schema my_custom_schema as well. When I do first migration I get the error. $ python manage.py migrate ... psycopg2.errors.InvalidSchemaName: no schema has been selected to create in LINE 1: CREATE TABLE "django_migrations" ("id" bigserial NOT NULL PR... ... How do I resolve it? Python version: 3.9.7 Django version: 3.2.8 Psycopg2 version: psycopg2-binary==2.9.1 PostgreSQL version: 12.8 -
Can I use requests library in Celery task?
I have a Django app where I have push notifications for users. The users are identified based on JWT token, no usernames or passwords are used. I have a Model to save an event to the database and I also have a route to send a notification tot he user. I use Celery to check the events from the database every n minute and now I should build the logic to send the event to the user based on for example the timestamp value of the event. I've created a task to tasks.py to check the events: @shared_task def get_events(): from .models import User, Notification users = User.objects.all() for user in users: events = Notification.objects.filter(id=user.id) if len(events) > 0: for event in events: api_call(user.id) This is only a skeleton as I'm trying to find a correct way to do this. My main problem at the moment is that I can get all the users and all the events but I don't know how to use requests library to do a request to the endpoint I have for sending notifications. Or, maybe the bigger question is: am I doing this right at all? Is there some better way to check the …