Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django TypeError: Field 'id' expected a number but got <User: >
I've migrated my database and I got the error of IntegrityError at /add/ NOT NULL constraint failed: base_notebook.user_id when trying to add a note. I put the camps of null and blank but still have this error: File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1823, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'User' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Gustavo\notepad\manage.py", line 22, in <module> main() File "C:\Users\Gustavo\notepad\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\schema.py", line 330, in add_field self._remake_table(model, … -
Facing ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid') -Django Rest + React
I have an Edit Profile page where a user can edit the previously entered information. The form also contains an image field. I fetch the data from the backend and prefill the fields with the existing data. Now the data that comes for the image is basically the path to the media folder where the image gets stored once uploaded. Now suppose the user does not want to change the previously entered image and submits the form I get the below error {'profile_photo': [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]} Please suggest to me what should I do to control this error if an image file is not received in the request.data Below are the codes views.py api_view(['PUT']) @permission_classes([IsAuthenticated]) @parser_classes([MultiPartParser, FormParser]) def edit_teacher_detail(request): data = request.data if data is not None: id = data.get('id') queryset = TeacherDetail.objects.get(id = id) serializer = TeacherDetailSerializer(instance=queryset, data = data) try: if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_200_OK) else: print(f'\nThis is the error in the serialization {serializer._errors}\n') return Response({'message': serializer._errors}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: print(e) return Response(status=500) reactjs API sending the data export const editTeacherDetail = async (detailsData, photo) => { let formData = new FormData(); formData.append("id", detailsData.id); … -
Can't deploy django application to Heroku - "App crashed" and gunicorn: command not found
Trying to deploy my first Django application to Heroku. I've followed a tutorial to set up my repo correctly and I've pushed the app. But when I try to open the app url on Heroku, this shows up instead: So I check the logs: 2022-05-12T14:14:01.000000+00:00 app[api]: Build started by user enders.game1990@gmail.com 2022-05-12T14:14:27.784940+00:00 app[api]: Release v12 created by user enders.game1990@gmail.com 2022-05-12T14:14:27.784940+00:00 app[api]: Deploy ff956b4a by user enders.game1990@gmail.com 2022-05-12T14:14:28.081101+00:00 heroku[web.1]: State changed from crashed to starting 2022-05-12T14:14:31.638069+00:00 heroku[web.1]: Starting process with command `gunicorn django_project.wsgi:application --log-file - --log-level debug` 2022-05-12T14:14:32.588066+00:00 app[web.1]: bash: gunicorn: command not found 2022-05-12T14:14:32.708993+00:00 heroku[web.1]: Process exited with status 127 2022-05-12T14:14:32.834316+00:00 heroku[web.1]: State changed from starting to crashed 2022-05-12T14:14:39.000000+00:00 app[api]: Build succeeded 2022-05-12T14:17:29.140662+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=django-blog-project-laila.herokuapp.com request_id=45751bb1-680f-40e1-a5fc-dcd7a54f1836 fwd="168.195.253.236" dyno= connect= service= status=503 bytes= protocol=https 2022-05-12T14:17:29.335494+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=django-blog-project-laila.herokuapp.com request_id=d947af74-2504-4e97-a847-17fa8c437ab9 fwd="168.195.253.236" dyn o= connect= service= status=503 bytes= protocol=https 2022-05-12T14:17:30.358991+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=django-blog-project-laila.herokuapp.com request_id=10313984-22b3-4951-bd98-776043f87afa fwd="168.195.253.236" dyn o= connect= service= status=503 bytes= protocol=https The part where it says gunicorn: command not found doesn't make sense because gunicorn is installed. Here's my requirements.txt file: asgiref==3.5.1 crispy-bootstrap5==0.6 Django==4.0.4 django-crispy-forms==1.14.0 gunicorn==20.1.0 Pillow==9.1.0 sqlparse==0.4.2 tzdata==2022.1 whitenoise==6.1.0 On settings.py I have the following: … -
Media Screen Alternative needed for WeasyPrint?
I have an image logo that has to be pasted on pdf at the top right. But I have both portrait and landscape pages on which the css doesn't work. Kindly help me with the issue as I want logo at the top right for both the orientations. Weasyprint does not help with media screens etc. Kindly, help me fixing the css so that both the orientations can have the logo. Thank you. @media print and (orientation: landscape){ #logo{ position: absolute; right: 10px; top: -5px; max-width: 100px; padding: 10px; } } @media print and (orientation: portrait){ #logo{ position: absolute; left: 650px; top: -5px; max-width: 100px; padding: 10px; } } {% if logo %} <img id="logo" src="{{logo}}" alt="Account Logo"> {% endif %} -
How to prehide from hrfe to make my iframe fully secret?
I'm currently developing a small system using django and bootstrap with the objective of generating links from powerBI reports to the users of the system, these reports are arranged in a panel with a button for each link attached to the user and when clicked, it transfers this link to the my iframe, with my current solution when pressing f12 it is impossible to see the link inside the iframe, it only appears unknow, but unfortunately when hovering the mouse over the button, the link appears at the bottom left of the screen, my question would be just how to remove this preview and how to prevent the link from being seen inside the button when pressing f12 -
Total like count in a post
I added a like/unlike button to my blog. It's working perfectly but I can't count the total number of likes present. What should I do now? How can I count the total number of likes? models.py: class FAQ(models.Model): likes = models.ManyToManyField(User,default=None, related_name="faqLIKES") views.py: def index(request): allFAQ = FAQ.objects.all() context = {"allFAQ":allFAQ} return render(request,'0_index.html',context) -
How to use add_form for Django admin?
How can i correctly use add_form in admin panel when class is inherited from admin.ModelAdmin. I find out the hack with overriding get_form method where you can dynamically change form to add_form value. With current approach i'm getting this error formsets, inline_instances = self._create_formsets(request, form.instance, change=False) AttributeError: 'UserForm' object has no attribute 'instance' form.py class AddCustomProductForm(forms.Form): users = forms.ChoiceField( label='Select a Profile', required=True, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["users"].choices = CustomUser.objects.all() admin.py class PostAdmin(admin.ModelAdmin): list_display = ('email', 'created', 'company_id',) add_form = AddCustomProductForm form = CustomProductForm fieldsets = ( (None, {"fields": ("users")}), ) def get_form(self, request, obj=None, **kwargs): defaults = {} if obj is None: defaults['form'] = self.add_form defaults.update(kwargs) return super().get_form(request, obj, **defaults) -
Django: How to enforce UniqueConstraint with parent and child models
Say I have the following models: class ParentModel(models.Model): parent_field_1 = models.CharField(max_length=10) parent_field_2 = models.CharField(max_length=10) class Meta: constraints = [ models.UniqueConstraint( fields=['parent_field_1', 'parent_field_2', 'child_field_2'], name='unique_parent_example' ) ] class ChildModel(ParentModel): child_field_1 = models.CharField(max_length=10) child_field_2 = models.CharField(max_length=10) I want to utilise the ParentModel's UniqueConstraint but apply an additional field within the ChildModel's UniqueConstraint. I know this is not possible but to help visualise the idea, I'd ideally like to do something like this: class ChildModel(ParentModel): [.. fields ..] class Meta: constraints = [ models.UniqueConstraint( fields=['parentmodel', 'child_field_2'], name='unique_child_example' ) ] Almost like I'm building the unique constraint as inheritance also. How could I do this? -
when running tests in django and PostgreSQL DB can't create database
I'm having a problem with running unit tests in django while using ElephantSQL, when running command python manage.py runserver everything works just fine, i'm able to connect to the server without any problem but when running the command python manage.py test i'm getting this error: C:\Users\Sman9\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\siteid running initialization queries against the production database when it's not needed (for example, when running tests). Djang warnings.warn( Got an error creating the test database: permission denied to create database Creating test database for alias 'default'... C:\Users\Sman9\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\postgresql\base.py:323: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. warnings.warn( Got an error creating the test database: permission denied to create database``` my databases setting in settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '####', 'USER': '#####', 'PASSWORD': '#############', 'HOST': 'chunee.db.elephantsql.com', 'PORT':'', } } } -
How to pass request object from one serializer class to other serializer class in Django
I want to access userId of current logged-in user. for that i need to pass the request object from one serialiser to another. Here's my code class ThreadViewSerializer(serializers.ModelSerializer): op = PostDetailViewSerializer(context={'request': request}) class Meta: model = Thread fields = ('id', 'title', 'op', 'group_id', 'type', 'reference_id', 'is_frozen', 'views', 'is_pinned') In PostDetailViewSerializer, I want to pass request object but for that it requires self object. like this request = self.context.get('request') Thus, How can we pass the request object to PostDetailViewSerializer class in ThreadViewSerializer class. Please help me in this. -
Django template JS variable 'safe' method not passing data to custom js file?
I'm trying to pass a google api key into my custom js file in Django, the function is for a AutoComplete google places api search , but at the moment it's not working, if I put the actual key directly into the .getScript function, like: https://maps.googleapis.com/maps/api/js?key=XXX&libraries=places" then the search function works, but with the current setup also intended to hide the api key, it doesn't work, I'm obviously missing something, appreciate any ideas? django settings: GOOGLE_API_KEY = "XXX" base.html <script src="{% static 'js/google_places.js' %}"></script> views.py {'google_api_key': settings.GOOGLE_API_KEY} google_places.js $.getScript("https://maps.googleapis.com/maps/api/js?key=" + "google_api_key" + "&libraries=places") .done(function( script, textStatus ) { google.maps.event.addDomListener(window, "load", initAutoComplete) }) let autocomplete; function initAutoComplete(){ autocomplete = new google.maps.places.Autocomplete( document.getElementById('autocomplete'), { types: ['country', 'locality'], }) } travel.html {% endblock content %} {% block js %} <script type="text/javascript"> var google_api_key = "{{google_api_key|safe}}"; </script> {% endblock js %} also the google_api_key variable is being passed into travel.html , I've checked that and it's working fine. -
Django s3: (403) when calling the HeadObject operation: Forbidden
I wish to allow registered users of a Django app to upload and view files to an s3 bucket. I can use the bucket to collect static images and view them on the site, but when I upload I get a 403 forbidden error. I've looked at the answers here to many similar questions and tried various different s3 bucket policy templates without success. How can I troubleshoot what is going on, and/or how can I get this working? All help grateful received. Two of the policies i have tried: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "s3:*", "Resource": [ "arn:aws:s3:::BUCKETNAME", "arn:aws:s3:::BUCKETNAME/*” ] } ] } { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": [ "arn:aws:s3:::BUCKETNAME/*" ] }, { "Effect": "Allow", "Principal": "*", "Action": "s3:GetBucketLocation", "Resource": [ "arn:aws:s3:::BUCKETNAME" ] } ] } From my settings.py AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' AWS_STATIC_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'notes/static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION) AWS_PUBLIC_MEDIA_LOCATION = 'media/public' DEFAULT_FILE_STORAGE = f'{ROOT_NAME}.storage_backends.PublicMediaStorage' AWS_PRIVATE_MEDIA_LOCATION = 'media/private' … -
How to search and filter on multiple related models?
I am creating an search and filter system in which user can type and search related courses and institutions. This is my model structure: Model Structure: Institutions: - Name - Id - email - address ...... etc. Courses: - owner = models.ForeignKey(Institution, on_delete=models.CASCADE) - name - ref - license - overview ..... etc Now by using the above, i have created a search bar in which user needs to type something and then press "search" button or else press "Enter" key. This will show search results. My search code: query = request.GET.get('q') courses = Course.objects.filter(name__icontains=query) institution= Institution.objects.filter(name__icontains=query) queryset_chain = chain(courses,institution) So the problem here is that, I want to display the result as follows. scenario 1: Lets say that course and Institution has same name like "tech". When user search for "tech", I need to show result as follows: Institution Name Course name scenario 2: Lets say that course has name as "tech" but not Institution has that name. When user search for "tech", I need to show result as follows: In this case, I need to show the Course name and also correspondant Institution name: Institution Name Course name scenario 3: where Institution has "tech" as name. But no … -
none type object has no attribute 'replace'
I'm trying to replace None with 0 but I'm getting an error as none type object has no attribute 'replace'. This is what I have tried views.py: def Activity(UserID): cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,)) result_set =cursor.fetchall() data = [] for row in result_set: TaskId = row[0] data.append({ 'TaskId':row[0], 'TaskName' : row[1], 'Source' : row[2], 'Requester' : row[3].replace('None', '0') if row[3] == None else row[3] , 'type' : row[4], 'IsActive':GetCurrentSubTaskSTatus(TaskId), }) print(data) return Response(data[0], status=status.HTTP_200_OK) -
CSRF token is generated in 127.0.0.1:3000 but not in hosted application
I have a question , when i check cookies in 127.0.0.1:3000 i see that the csrf token is present in those cookies like the picture bellow . But when i check it in the hosted app it doesn't appear and i will not be able to get it to perform authentication . i had the same problem with localhost:3000 so how i can fix this problem ? -
Django - Create downloadable Excel file using Pandas & Class Based View
I'm relatively new to Django and have been looking for a way to export my DataFrame to Excel using Pandas and CBV. I have found this code: from django.http import HttpResponse def my_view(request): # your pandas code here to grab the data response = HttpResponse(my_data, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="foo.xls"' return response It's perfect for a FBV model but how can I manage to tweak it to pass it into get_context_data? Here's my code: class ResultView(TemplateView): template_name = 'tool/result.html' # def get(self, request, *args, **kwargs): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.request.user context['result'] = self.request.session['result'] result = context['result'] # Transformation into DF df = pd.DataFrame(result) #to be transformed into Excel File # pprint(df) # Count number of rows nb_rows = df[df.columns[0]].count() context['nb_rows'] = nb_rows # Count number of rows which are errored nb_errors = np.sum(df['IsSimilar'] == True) context['nb_errors'] = nb_errors # Sum all rows total_amount = df['Montant_HT'].sum() context['total_amount'] = total_amount # Sum all rows which are errored rows_errors_sum = df.loc[df['IsSimilar'] == True, ['Result']].sum().values rows_errors_sum = str(rows_errors_sum).replace('[', '').replace(']', '') rows_errors_sum = float(rows_errors_sum) context['rows_errors_sum'] = rows_errors_sum return context I can't manage to make the request within my class ResultView. Could you help me with that? -
Django migration conflict between git branches
Is there any way to adequately merge migrations in django if they happen to be in two different branches in git? So far we have just avoided this -
Django, Postgresql: Deleted some db tables because I didn't want them, created new in Django, can't migrate now
I decided to change the models as they were initially designed, so I didn't want the old tables located in postgresql. I deleted them. I deleted them because otherwise they would be superfluous. But now I can't migrate because Django keeps references to the old tables. My web does make use of the registration authentication db tables so I am wary about doing something drastic like deleting the migrations folder. This is just about the last messages from the console. File "C:\Users\chefv\WEBS\registro\registro\lib\site-packages\django\db\utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\chefv\WEBS\registro\registro\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "users_electricity" does not exist -
google.maps.event.addDomListener() is deprecated, use the standard addEventListener() method instead : Google Place autocomplete Error
I am trying to add Google place auto suggest, I copied the code from the developer's website to try it out but got the error : google.maps.event.addDomListener() is deprecated, use the standard addEventListener() method instead. Also I am not getting any place suggestions. https://developers.google.com/maps/documentation/javascript/places-autocomplete google.maps.event.addDomListener(window, 'load', initializeAutocomplete); i have also added script <script src="https://maps.googleapis.com/maps/api/jskey=api_key&libraries=places"></script> I have implemented the same thing in one html it worked successfully, but when I used it on click button which opens a popup (form which has place-input), it gave me this error. Note : I have also tried addEventListener but that's giving me an error : google.maps.event.addEventListener is not a function Do you have any idea why I am getting this error, and how can I fix this? -
sequence item 1: expected str instance, property found
I am working Django app and I came cross where I need to extract a value of booking and pass it to another function to print a pdf doc with some details fields including a total amount of the booking ## defe function to extract deal total amount and to avoid circular import @property def extract_deal_total_amount(): from sook_contact.signals import on_loading_booking_deal deal_values = on_loading_booking_deal('8388945051') convert_to_float = float(deal_values['amount']) * 1.20 return str(convert_to_float) // the in another function elif field_name == OccupationLicenseFieldType.BOOKING_FEE.value: return extract_deal_total_amount -
How Can I get Model record through ID into Django FormView for submition into another Model
I am new to Django and I am working on a Deposit and Withdrawal Project where I am using FormView (Class Based Views) to add Deposit for customers. I have list of customers with a button for deposit where I want that; any time the Deposit button is clicked a form should be displayed with some fields like account number should be disabled and only deposit amount form field active. And once the form is submitted, the record should be add to the deposit table for that customer. Here is my models code: class Customer(models.Model): surname = models.CharField(max_length=10, null=True) othernames = models.CharField(max_length=20, null=True) accountnumber = models.CharField(max_length=10, null=True) address = models.CharField(max_length=30, null=True) phone = models.CharField(max_length=11, null=True) date = models.DateTimeField(auto_now_add=True, null=True) #Get the url path of the view def get_absolute_url(self): return reverse('customer_create', args=[self.id]) #Making Sure Django Display the name of our Models as it is without Pluralizing class Meta: verbose_name_plural = 'Customer' # def __str__(self): return f'{self.surname} {self.othernames} - {self.accountnumber}' class Deposit(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) deposit_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('create_account', args=[self.id]) def __str__(self): return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}' Here is my code for my form: class CustomerDepositForm(forms.ModelForm): #Set Read … -
psycopg2 installing error in cPanel while hosting Django Website with PostgreSQL
Collecting psycopg2 Using cached psycopg2-2.9.3.tar.gz (380 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [23 lines of output] running egg_info creating /tmp/pip-pip-egg-info-irgb8yga/psycopg2.egg-info writing /tmp/pip-pip-egg-info-irgb8yga/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-irgb8yga/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-irgb8yga/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-irgb8yga/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. -
How to query a specific field in a model that has the same name as another field of another model
I'm trying to render the device that has the same name as the Gateway in the query so I created three models (The plant model has nothing to do with this issue so skip it ) as you can see in the models.py : from django.db import models infos_type= ( ('ONGRID','ONGRID'), ('PV','PV'), ('HYBRID','HYBRID'), ) infos_status= ( ('etude','Etude'), ('online','Online'), ('Other','Other'), ) infos_Device= ( ('Rs485','Rs485'), ('lora','lora'), ('Other','Other'), ) class new_Plant(models.Model): name=models.CharField(max_length=20) adress=models.CharField(max_length=50) type=models.CharField(max_length=20,choices=infos_type) location=models.CharField(max_length=50) list_gateway=models.CharField(max_length=50) status=models.CharField(max_length=50,choices=infos_status) def __str__(self): return self.name #class Meta: #db_table="website" class new_Gateway(models.Model): gatewayname=models.CharField(max_length=20) slavename=models.CharField(max_length=20) list_devices=models.CharField(max_length=20) def __str__(self): return self.gatewayname class new_Device(models.Model): Gateway_Name=models.CharField(max_length=20) DeviceName=models.CharField(max_length=20) slavename=models.CharField(max_length=20) adress=models.CharField(max_length=20) baud_rate=models.CharField(max_length=20) connection_type=models.CharField(max_length=20,choices=infos_Device) def __str__(self): return self.DeviceName # Create your models here. Now as I said I want to render in a specific page , the device that Has "Gateway_Name" field same as the Gateway "gatewayname" field. in my views.py this is what I tried but it doesn't work : def gatewaysdevice(request,id): gateway=new_Gateway.objects.get(id=id) result=new_Device.objects.filter(Gateway_Name__contains=new_Gateway(gatewayname)) return render(request, 'website/gatewaysdevice.html',{'result':result}) -
Passing django.core.mail.EmailMultiAlternatives instance as async_task with Django-Q
An E-mail template is build-up and send weekly to more than 2000 email recipients (bcc). I must run it as background since it takes few minutes to get rendering back and that some E-mail provider block Senders because of mass mail in a few period of time. I cannot use SendinBlue or MailChimp or any others for contractual reasons. I use 'django.core.mail.EmailMultiAlternatives' instance in order to add images '(self.attach(img)' and documents '(self.attach_file(filepath)'. After creation all context data like <img src="cid:filename.jpg". I use render_to_string(template_name, request=request, context=context).strip() to get back my filled-in HTML E-mail template. Background running with async_task of Django-Q When I pass my EmailMultiAlternatives instance, I get the error: Traceback (most recent call last): File ".pyenv/versions/3.9.7/lib/python3.9/multiprocessing/queues.py", line 245, in _feed obj = _ForkingPickler.dumps(obj) File ".pyenv/versions/3.9.7/lib/python3.9/multiprocessing/reduction.py", line 51, in dumps cls(buf, protocol).dump(obj) TypeError: cannot pickle '_thread.RLock' object If I build my instance template in the task (but with code redundancy), it works but then since I want to loop over my 2000 recipients to send the mail by chunk of 99 every n minutes (avoid mail server blocking), again, I need to pass the EmailMultiAlternatives instanceas a parameter and I get back the same error. Any idea on how to proceed? -
Pass Django variables to javascripts
I am stuck into a problem, I want to pass django variable to javascripts but I can't. views.py def dashboard_view(request): months_before = 5 now = datetime.utcnow() from_datetime = now - relativedelta(months=months_before) modified_from_datetime = from_datetime.replace(day=1, hour=0, minute=0, second=0, microsecond=0) month = Btdetail.objects.filter(DatePur__gte=modified_from_datetime).count() return render(request, "dashboard.html", {'month': month}) I want to embed month value to javascripts data my html script function is <script> var xValues = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; new Chart("myChart3", { type: "line", data: { labels: xValues, datasets: [{ data: [5,10,20,15,20,5,15,40,10,12,24,35], borderColor: "red", fill: false }] }, options: { legend: {display: false} } }); </script> actually I want to create a Area bar, all things are good but javascript functions cant get value from django database and if there is another way to do this please tell me [1]: https://i.stack.imgur.com/9bJzE.jpg