Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to fixed this error ,,( please help me,)
Error running WSGI application ModuleNotFoundError: No module named 'project' File "/var/www/sanjoy_pythonanywhere_com_wsgi.py", line 14, in application = get_wsgi_application() wsgi.py # To use your own django app use code like this: import os import sys # ## assuming your django settings file is at '/home/sanjoy/mysite/mysite/settings.py' ## and your manage.py is is at '/home/sanjoy/mysite/manage.py' path = '/home/sanjoy/project' if path not in sys.path: sys.path.append(path) # os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' # ## then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
What is even use of Django Nested Atomic?
I recently came across nested atomic blocks in Django and it looks like even if error occurs in any of those blocks, all of them will be rollbacked. So, why do people use nested atomic block? Specifically, what is the difference between with transaction.atomic(): do_something with transaction.atomic(): do_something_more and with transaction.atomic(): do_something do_something_more ? If there is no overall difference, then in what scenario first should be used instead of second? -
Make form field dropdown dependable in Django
I am currently working on Django admin modification. I made an app which has an inventory model containing some fields. There I have category and subcategory fields as dropdown. I have some category and under those category I have corresponding subcategory. What I want is to when I select category say for example I choose category-1 it should populate the subcategory dropdown fields with only those subcategory which is under the category-1. I found some explanation regarding this, they were working with ajax and stuffs with the custom form but not with the admin generated forms. As I am new to admin modification I found it hard to where I need to change and etc. -
Issue with bcrypt, py-bcrypt and django-bcrypt
i have installed bcrypt==4.0.1 , py-bcrypt==0.4 and django-bcrypt==0.9.2 in my django project virtual env. When am trying to run createsuperuser command then its giving me following error AttributeError: module 'bcrypt._bcrypt' has no attribute 'encode_base64' Any idea how can i fix this? I have tried multiple versions of bcrypt module but it did not worked -
Why get i message `side of a many-to-many set is prohibited. Use ....set() instead` in django-pytest?
I'm a learning the django - pytest. I'm read the forum? but i don't find the answered. Pleas help me. Task: create a test for the api request (django-pytest). I use the two basic library: Model Bakery Pytest-Django , and other classes, it's API Client, random. The 'Course' model has the relation many-to-many I generating the content for db through - 'Model Bakery' and after i insert when filling the db But i'm can't understand When i start the test, i get error short test summary info FAILED tests/students/test_courses_api.py::test_example - TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use student.set() instead. 1 failed, 1 warning in 9.86s Why get i message side of a many-to-many set is prohibited. Use student.set() instead ? What did i wrong if in documentation writes about make_m2m=True: By default Model Bakery doesn’t create related instances for many-to-many relationships. If you want them to be created, you have to turn it on as following: @pytest.mark.django_db() def test_example( name_stude = get_name_random, # the example is down title = get_courses_random, username = getUser, # the example is down api_client = api_client # the example is down ): #Arrange student = baker.make( "students.Student", name … -
how to install xhtml2pdf in python 3.11
i was using xhtml2pdf in django python 3.10 which was working well. now i upgraded my python version to 3.11. i tried to install pip intall xhtml2pdf, i get error ********************************************************************************* Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? ********************************************************************************* I already updated pip, setuptools and installed pillow, wheel.i already installed microsoft visal c++ 2015. i am unable to install libxml2. I do not know where to find a currect file and how to install. i am using windows 11 pro 64 Bit. Please help me. to install xhtml2pdf in python 3.11 -
How to find way of automatic delete tem dir and files after debagging tests in Django?
Django project. In this project unittests. After debagging process have made temp dir and files, and don'n delete automatically. sys MacOs. After test temp dir and files are deleted, but after debugging this test they still there. test example: @override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT) class PostCreateFormTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.small_gif = ( b'\x47\x49\x46\x38\x39\x61\x02\x00' b'\x01\x00\x80\x00\x00\x00\x00\x00' b'\xFF\xFF\xFF\x21\xF9\x04\x00\x00' b'\x00\x00\x00\x2C\x00\x00\x00\x00' b'\x02\x00\x01\x00\x00\x02\x02\x0C' b'\x0A\x00\x3B' ) cls.uploaded_image = SimpleUploadedFile( name='small.gif', content=cls.small_gif, content_type='image/gif' ) @classmethod def tearDownClass(cls): super().tearDownClass() shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True) def test_create_post_form_valid_by_authorized_user(self): posts_count = Post.objects.count() form_data = { 'text': 'Тестовая запись', 'group': self.group.id, 'image': self.uploaded_image } response = self.authorized_client.post( reverse('posts:post_create'), data=form_data, follow=True ) self.assertEqual(Post.objects.count(), posts_count + 1) self.assertTrue( Post.objects.filter( text=form_data['text'], group=form_data['group'], image='posts/small.gif' ).exists() ) redirect = reverse( 'posts:profile', kwargs={'username': self.user.username}) self.func_redirect_and_tests_post_correct_created_form_fields( response, form_data, redirect) Find a way to make delete process temp files automatically . -
DRF How to perform additional operations on an instance
Which of the given ways of writing additional logic is technically correct? The example includes changing the status of the document. After a quick reserach of similar questions, I understand that there are 3 possibilities described below. However, no answer describes which solution is used during daily practicals, and the examples from the documentation do not dispel doubts. Please help. Providing custom data to the serializer and the standard model serializer: class PZSaveAPIView(APIView): @transaction.atomic def patch(self, request, pk, format=None): document = get_object_or_404(PZ, pk=pk) print(request.data) serializer = PZModelSerializer( document, data={'status': 'E'}, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) After the object is serialized, change the status: class PZSaveAPIView(APIView): @transaction.atomic def patch(self, request, pk, format=None): document = get_object_or_404(PZ, pk=pk) serializer = PZModelSerializer( document, data=request.data, partial=True) if serializer.is_valid(): pz = serializer.save() pz.status = 'S' pz.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Contain the logic in the serializer, and the view stays basic: class PZUpdateSerializer(serializers.ModelSerializer): class Meta: model = PZ fields = '__all__' def update(self, instance, validated_data): instance.status = 'S' instance.save() return instance Is it even necessary to use a serializer in such cases? Example: class PZSaveAPIView(APIView): def patch(self, pk): document = get_object_or_404(PZ, pk=pk) document.set_status_saved() document.save() return Response('Document saved') -
Calculating the sum of TimeField values in Django
Here I am using Django 3.0 and Python 3,7 Here I need to calculate all the values of TimeField whose day_type='Weekdays' Here is my models.py class WorkTime(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE) day_type = models.CharField(max_length=200, blank=True, null=True, choices=DAY_TYPE_CHOICES) start_time = models.DateTimeField() finish_time = models.DateTimeField() total_time = models.TimeField(blank=True, null=True) class ProductionCapacity(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE) date = models.DateTimeField(blank=True, null=True) number_of_people = models.IntegerField(blank=True, null=True) capacity = models.TimeField(blank=True, null=True) work_time = models.ForeignKey(WorkTime,on_delete=models.CASCADE,blank=True,null=True) Here is my views.py class ProductionCapacityCreateView(CreateView): template_name = 'manufacturing/production_capacity_form.django.html' form_class = ProductionCapacityForm context_object_name = "production_capacity" model = ProductionCapacity def get_form_kwargs(self): kwargs = super(ProductionCapacityCreateView, self).get_form_kwargs() kwargs["client"] = self.request.user.client kwargs["request"] = self.request return kwargs def form_valid(self, form): self.client = self.request.user.client self.object = form.save(commit=False) self.object.client = self.request.user.client num_of_people = form.cleaned_data['number_of_people'] date = form.cleaned_data['date'] myDate = datetime.datetime.strptime(str(date), "%Y-%m-%d") weekno = myDate.weekday() if weekno < 5: print("Today is a Weekday") work_time = WorkTime.objects.filter(client=self.client,day_type='Weekdays').values_list('total_time',flat=True) c_time = sum(work_time) self.object.capacity = number_of_people * c_time else: pass try: self.object.save() messages.success(self.request, 'Day created successfully.') except BaseException as e: logger.exception(e) messages.error(self.request, 'Failed to create a day.') return HttpResponseRedirect(reverse("capacity_list")) Here is my error traceback Traceback (most recent call last): File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = … -
filtering products by categories [PROBLEM]
I got a problem with filtering products by categories. My issue is I want to order my products by "category" as I've made in my JSON file. If a customer would click "Amulets" the page shows only products with category "Amulets". How to do that? I guess I should to use "Filter" but I'm a beginner so I don't know how to. Thanks a lot for any help! much appreciate it! I've tried to use product.filter but I can't ;/ thanks for help! -
django.db.utils.OperationalError: no such table: product, django cannot import form.py into view.py
I've 3 pages Model, Forms and View In model.py i define my table #model.py class Prod(models.Model): id = models.CharField(primary_key=True, max_length=10, blank=False, null=False) description = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'product' verbose_name = 'PROD' now I move to forms.py #forms.py from .models import Prod class ProdForm(forms.ModelForm): #some code to fill class Meta: model = Prod exclude = [...] widgets = { ... } labels = { ... } and finally with view.py #view.py from .forms import ProdForm When i execute python manage.py makemigrations, I get an error saying no such table: product my app was hosting locally with postgres, now i used db.sqlite3 to test, i don't undestand why views.py can't import the table forms or at least why It's not creating them? I don't understand why, specially that this code was running locally with a postgres. -
Compare data and time in Django Framework
I have an application. I would like to compare date and time when a user create a job list. The job date should not be earlier than current date, and finish time should not be earlier than start time, and if a job happens at night,e.g. start at 22:00 in the evening and finish at 7:00 the next day in the morning, how should I compare them? I am not sure about the logic, where should I put this comparison function? In model or view? This is my code: class Job(models.Model): pub_date=models.DateTimeField('Date published',auto_now_add=True) updated_date = models.DateTimeField(auto_now_add=True,null=True, blank=True) job_date=models.DateTimeField('Date') start_time = models.TimeField() finish_time = models.TimeField() published = models.BooleanField(default=False) details=models.CharField(max_length=200, blank=True, null=True) user=models.ForeignKey(get_user_model(),on_delete=models.CASCADE,null=True,blank=True) # the user could be employer, admin, staff or nurse. And if nurse reserves the shift, this field will be the same as nurse field. time_reserved = models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return f'{self.pub_date}' #view def createJob(request): user=request.user employer=Employer.objects.all() form = JobForm() if request.method == 'POST': #print('Printing POST:', request.POST) form = JobForm(request.POST) if form.is_valid(): #to do1, one employer could not create job for other employers.# #to do 2. date can't be past time, finish time could not be earlier than start time if request.user.is_employer: employer=request.user form.save() messages.success(request, "The job has been … -
Vscode debugger not working with python2 and django 1.7
I am trying to run my django application with vscode debugger but its not working(nothing happens) What i did is select the python interpreter (/usr/bin/python2) and hit the run and debug. After hitting run and debug nothing happens but in the terminal output it was like this (DAP Server launched with command: /usr/bin/python2 /home/me/.vscode/extensions/ms-python.python-2022.18.1/pythonFiles/lib/python/debugpy/adapter) The same config works fine if i select the python interpreter (usr/bin/python3). launch.json { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "console": "integratedTerminal", "args": [ "runserver", ], "django": true }, -
How to parse a xml file in Django and store the data as a JSON object?
I have a xml file and I want to parse it based on its Root id. The root should be converted into a new JSON key value pair. ` <objects> <record> <organization>Marvel</organization> <code>2005</code> <name>Iron-Man</name> <address_1>New York</address_1> <address_2/> </record> <objects> ` This is a sample of my xml file. After parsing this data into a JSON object, I want to obtain a result like this: ` {"record": [ "organization": "Marvel", "code": 2005, "name": "Iron-Man", "address_1": "New York", "address_2": "" ] } `I have used the following codes: Models.py: from Django.dB import models class Records(models.Model) value = JSONField()` code.py: `from my.app.models import Record import xmle.tree.Elementtree as ET def save(): file = "xml.xml" data = ET.parse(data) root = data.findall('record') for i in root: organization = i.find('organization').text code = i.find('code').text name = i.find('name').text address_1 = i.Find('address_1').text address_2 = i.Find('address_2').text x = Record. objects.create( organization =organization,code=code,name=name,address_1 = address_1,address_2 = address_2) x.save()` but this code extracts data from the particular field store data as such. I need to know how to store all data from 'record' into a single json object. -
Dynamic nested formsets Django
i have a django project with a circuit model and an exercise model (circuit has an exercise field which is Many2Many relationship to exercise model. I want each user to be able to dynamically add circuits and to each circuit dynamically add exercises, so each circuit will have the exercises added to it specifically. I managed to dynamically add the 2 formsets (circuitFormSet and exerciseFormSet) with javascript but couldn't connect between the circuits and exercises. models.py: class Exercise(models.Model): name = models.CharField() num_of_rounds = models.IntegerField() class Circuit(models.Model): name = models.CharField() exercises = models.ManyToManyField(Exercise) forms.py class ExerciseForm(ModelForm): class Meta: model = Exercise fields = '__all__' class CircuitForm(ModelForm): class Meta: model = Circuit fields = '__all__' ExerciseFormSet = formset_factory(ExerciseForm, extra=1) CircuitFormSet = formset_factory(CircuitForm, extra=1) -
django filterset search object that contain text
I'm not experience with python or django before. but I just started to create new custom plugin for NetBox using django the plugin works well but I still struggle with search function. I can search if the values are text. but if the value is an object, it not able to search in the postgresql, the table I've created with member show as member_id that refer to ipam_ipaddress(id) models class memberlist(NetBoxModel) member = models.ForeignKey( to='ipam.IPAddress', related_name='member', verbose_name='Member IP Address', on_delete=models.PROTECT ) filtersets class memberlistFilterSet(django_filters.FilterSet): q = django_filters.CharFilter( method="search", label="Search", ) class Meta: model = memberlist fields = [ 'name', 'member', ] def search(self, queryset, name, value): if not value.strip(): return queryset qs_filter = ( Q(name__icontains=value) |Q(member_icontains=value) ) return queryset.filter(qs_filter) Please help!! I want to search by name or member value that references to IPAddress model in NetBox I've tried many method but it didn't work e.g. member = IPAddress.objects.filter(address__contains=) -
Celery worker connection with Rabittmq met broken pipe error IN Gevent Mode
This does not happen with our dev environment, tasks there run on a much smaller db, so issuing much less db queries and external requests, I imagine this issue might have something to do with task loads. error: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/celery/worker/consumer/consumer.py", line 246, in perform_pending_operations self._pending_operations.pop()() File "/usr/local/lib/python3.8/site-packages/vine/promises.py", line 160, in __call__ return self.throw() File "/usr/local/lib/python3.8/site-packages/vine/promises.py", line 157, in __call__ retval = fun(*final_args, **final_kwargs) File "/usr/local/lib/python3.8/site-packages/kombu/message.py", line 128, in ack_log_error self.ack(multiple=multiple) File "/usr/local/lib/python3.8/site-packages/kombu/message.py", line 123, in ack self.channel.basic_ack(self.delivery_tag, multiple=multiple) File "/usr/local/lib/python3.8/site-packages/amqp/channel.py", line 1407, in basic_ack return self.send_method( File "/usr/local/lib/python3.8/site-packages/amqp/abstract_channel.py", line 70, in send_method conn.frame_writer(1, self.channel_id, sig, args, content) File "/usr/local/lib/python3.8/site-packages/amqp/method_framing.py", line 186, in write_frame write(buffer_store.view[:offset]) File "/usr/local/lib/python3.8/site-packages/amqp/transport.py", line 347, in write self._write(s) File "/usr/local/lib/python3.8/site-packages/gevent/_socketcommon.py", line 699, in sendall return _sendall(self, data_memory, flags) File "/usr/local/lib/python3.8/site-packages/gevent/_socketcommon.py", line 409, in _sendall timeleft = __send_chunk(socket, chunk, flags, timeleft, end) File "/usr/local/lib/python3.8/site-packages/gevent/_socketcommon.py", line 338, in __send_chunk data_sent += socket.send(chunk, flags) File "/usr/local/lib/python3.8/site-packages/gevent/_socketcommon.py", line 722, in send return self._sock.send(data, flags) BrokenPipeError: [Errno 32] Broken pipe This is my celery command: celery -A analytics worker -P gevent -c 500 -l info -E --without-gossip --without-mingle --without-heartbeat & and my Django configs: CELERY_IGNORE_RESULT = True CELERY_WORKER_PREFETCH_MULTIPLIER = 100 CELERY_WORKER_MAX_TASKS_PER_CHILD = 400 CELERYD_TASK_SOFT_TIME_LIMIT = 60 * … -
While converting HTML to pdf, the page is stuck in loading at create pdf
While trying to generate a pdf file with the below code, the browser is stuck loading from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() print('RESULT') pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) print('PDF') if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None and generate_pdf view: def generate_pdf(request): pdf = render_to_pdf('doc.html', data) response = HttpResponse(pdf, content_type='application/pdf') filename = "Document_to_mail.pdf" content = "inline; filename=%s" %(filename) download = request.GET.get("download") if download: content = "attachment; filename=%s" %(filename) response['Content-Disposition'] = content return response browser is stuck in pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) -
Product Pop-up using Reach and Django
I am working through a tutorial on React and creating an ecommerce store with a Django backend. I am new to React. I have been able to get the React "FrontEnd" home page to display the products from the Django "products.py" which is a simple JSON file stored in the Django file system using the React Axios library. There is a product pop-up which displays the product information when the use clicks on the view button. I can't work out how to direct the pop-up to the "products.py" file. It is still drawing its information from the products.js in the React "FrontEnd" file system. The code is below. Any assistance would be appreciated. The code for the product page is below. Bestsellershop.js import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { handleOutofStock } from '../../../helper/shopHelper'; import { RatingShop } from '../../../helper/helper'; import Quickview from '../../layouts/Quickview'; import { Modal } from 'react-bootstrap'; import axios from 'axios' class Bestsellershop extends Component { constructor(props) { super(props); this.state = { error:null, modalshow: false, lastActiveBox: -1, data:[] } this.modalShow = this.modalShow.bind(this); this.modalClose = this.modalClose.bind(this); } componentDidMount(){ var str = "GeeksforGeeks"; this.setState({loading:true}); axios .get('/api/products/') .then(res=>{ console.log(res.data); this.setState({data:res.data, loading:false}); }) .catch(err … -
AttributeError at /login 'str' object has no attribute '_meta'
Guys i'm getting error in django login can you please help me to solve this error View.py def login_user(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, username) return render(request, 'auth/login.html') login.html <form method="post"> {% csrf_token %} <div class="mb-3"> <label for="username" class="form-label">Username</label> <input type="text" name="username" class="form-control" id="username"> </div> <div class="mb-3"> <label for="password" class="form-label">Password</label> <input type="password" name="password" class="form-control" id="password"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> -
django manage static files accessibility
example app tree: articles ├── admin.py ├── apps.py ├── models.py ├── static │ ├── css │ │ ├── article_change.css │ │ ├── article_create.css │ │ ├── article_detail.css │ └── js (obfuscated) │ ├── article_create.js │ ├── article_list.js │ ├── edit_process.js │ ├── editor.js │ └── js (readable) │ ├── article_create.js │ ├── article_list.js │ ├── edit_process.js │ └── editor.js ├── templates │ └── articles │ ├── article_create.html │ ├── article_detail.html │ ├── edit_process.html │ └── editor.html ├── tests.py ├── urls.py └── views.py static/js/js contains javascript that is human readable static/js contains obfuscated javascript files. I wrote a template tag to includes files: @register.simple_tag def jstatic(path): s = '' if settings.DEBUG: s = 'js/' return static(s + path) in templates, I can do: <script src="{% jstatic 'js/info.js' %}"></script> which conditionally renders static javascript files based on DEBUG mode. whereas, if not in DEBUG mode, will serve obfuscated files. the thing is, I don't want unobfuscated file to be accessed when DEBUG is not on, which is running the application on server. when debug is on, I want user user only to visit obfuscated files: static/js/js/info.js and have no access to static/js/info.js all the apps follows this root tree convention, I wonder … -
405 HTML: Method Not Allowed
I have created a calendar that is embedded in my website. There is an option for admins to create events and when I try to create an event, I get faced with a 405 Error. Could someone please point me in the right direction into why this isn't working, when in previous versions of Python Django, it was working? My code is below for convenience: urls.py from django.urls import path from main_website import views from main_website.views import (AboutView, ArticleCreateView, ArticleDeleteView, ArticleUpdateView, CalendarView, ContactUsView, DonateView, EditEventView, EventView, HelpUsView, ImageAddView, ImageCategoryAddView, ImageDetailView, ImageGalleryView, IndexView, SearchView, TaggedView) urlpatterns = [ path('', IndexView.as_view(), name='main_website_home'), path('about', AboutView.as_view(), name='main_website_about'), path('search/', SearchView.as_view(), name='main_website_search'), path('article_create', ArticleCreateView.as_view(), name='main_website_article_create'), path('article/<slug:slug>', views.article_detail, name='main_website_article_detail'), path('article/update/<slug:slug>/', ArticleUpdateView.as_view(), name='main_website_article_update'), path('article/delete/<slug:slug>/', ArticleDeleteView.as_view(), name='main_website_article_delete'), path('tags/<slug:slug>/articles/', TaggedView.as_view(), name="main_website_article_tags"), path('calendar/', CalendarView.as_view(), name='main_website_calendar'), path('calendar/event/new/', EventView.as_view(), name='main_website_calendar_new_event'), path('calendar/event/edit/<event_id>/', EditEventView.as_view(), name='main_website_calendar_edit_event'), path('waiting_list/register', views.waiting_list_register, name='main_website_waiting_list_register'), path('gallery', ImageGalleryView.as_view(), name='main_website_gallery'), path('gallery/upload', ImageAddView.as_view(), name='main_website_gallery_upload'), path('gallery/category/add/', ImageCategoryAddView.as_view(), name='main_website_gallery_add_category'), path('gallery/image/<str:pk>/', ImageDetailView.as_view(), name='main_website_gallery_image_detail'), path('help_us', HelpUsView.as_view(), name='main_website_help_us'), path('ways_to_donate', DonateView.as_view(), name='main_website_ways_to_donate'), path('contact_us', ContactUsView.as_view(), name='main_website_contact_us') ] utils.py import calendar from calendar import HTMLCalendar from datetime import date, datetime, timedelta from main_website.models import Event class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, … -
Django.db.utils.DatabaseError with MongoDB as Backend Database
Internal Server Error: /loginapi/registeruser/ Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\sql2mongo\query.py", line 929, in _insert query.execute() File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\sql2mongo\query.py", line 397, in execute res = self.db[self.left_table].insert_many(docs, ordered=False) File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\collection.py", line 770, in insert_many blk.execute(write_concern, session=session) File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\bulk.py", line 533, in execute return self.execute_command(generator, write_concern, session) File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\bulk.py", line 366, in execute_command _raise_bulk_write_error(full_result) File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\bulk.py", line 140, in _raise_bulk_write_error raise BulkWriteError(full_result) pymongo.errors.BulkWriteError: batch op errors occurred, full error: {'writeErrors': [{'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: PP1.loginapi_user index: email_1 dup key: { email: "m@gmail.com" }', 'keyPattern': {'email': 1}, 'keyValue': {'email': 'm@gmail.com'}, 'op': {'id': 18, 'last_login': None, 'is_superuser': False, 'first_name': '', 'last_name': '', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2022, 11, 8, 7, 7, 44, 901495), 'name': 'g', 'email': 'm@gmail.com', 'password': '', '_id': ObjectId('636a0040d416e6cc888d66d5')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []} The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__ self._query = self.parse() File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\sql2mongo\query.py", line 869, in parse raise exe from e djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: INSERT INTO … -
windows 11 - python 3.11.0 - error installing psutil, How to resolve?
note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for psutil Failed to build psutil ERROR: Could not build wheels for psutil, which is required to install pyproject.toml-based projects I was trying to install locust in Tastypie Project. The requirements used in project are :- -
python app setup option from cPanel software section is missing
I bought a domain and hosting from webhost python for my Django web site but python app setup option from cPanel software section is missing and, in every tutorial, they follow the same the step means without python app setup option I have no way to live my Django site, I am completely new in web development and this first time I want live my website I try to follow my YouTube tutorial, but everyone follows same steps so don't understand what should i do