Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrating Django and Socket Communication in a Kivy Chat Application
I've developed a chat application using Kivy. Within the application, the server and client establish communication via pythons built-in socket. While it functions adequately, I'm considering incorporating Django on the server side. Navigating through various libraries like pythons built-in socket, Django WebSocket, and websockets has left me somewhat perplexed. I would greatly appreciate your assistance in clarifying at least one of the following queries: 1- Could you elucidate the distinctions between pythons built-in socket, socketio, and websockets in Django, as well as the websockets library in Python? 2- Is it feasible to employ different libraries on the client and server sides, such as using pythons built-in socket (or websockets) on the client side and Django WebSocket on the server side? 3- Does Django Channels offer support for Python's native socket, rather than relying exclusively on channel websockets? 4- Is it plausible to integrate Django into a Python chat application centered around pyhon socket, leveraging its functionalities for user authentication, database management, and static content handling in conjunction with real-time communication? -
Django post request failing silently
I have a Django - React project. I am having an issue where one of my post APIs is throwing an error message which I am not being able to resolve. Following is the class from my views.py class OrdersList(generics.ListCreateAPIView): queryset = models.Order.objects.all() serializer_class = serializers.OrderSerializer Following is the urls.py path('orders/', views.OrdersList.as_view()), Following is the post call from react.js const formData = new FormData(); formData.append('customer_id', customerId); axios.post(createOrderUrlRef.current, formData).then((response) => { console.log(`${TAG} ${JSON.stringify(response)}`); }).catch((error) => { console.log(`${TAG} error: ${JSON.stringify(error)}`); }); My environment is currently DEBUG and I see following error in console of Firefox, OrderConfirmation error: {"message":"Request aborted","name":"AxiosError","stack":"AxiosError@http://localhost:3000/static/js/bundle.js:88555:18\nhandleAbort@http://localhost:3000/static/js/bundle.js:87934:14\..."headers":{"Accept":"application/json, text/plain, */*"},"method":"post","url":"http://127.0.0.1:8000/api/orders/","data":{}},"code":"ECONNABORTED","status":null} There is no error message seen in django console. -
Cannot assign "'12'": "Receive.registerleson" must be a "Registerleson" instance
error : ValueError at /operation/member/RecivVoucher/339/ Cannot assign "'3'": "Receive.registerleson" must be a "Registerleson" instance. model : class Receive(models.Model): student = models.ForeignKey("user.Profile", on_delete=models.CASCADE, verbose_name='زبان آموز', related_name='receives') factor = models.ForeignKey("product.Factor", on_delete=models.CASCADE, verbose_name='فاکتور', null=True, blank=True) registerleson = models.ForeignKey("member.Registerleson", on_delete=models.CASCADE, verbose_name='ثبت نام', null=True, blank=True) term = models.ForeignKey("term.Term", on_delete=models.CASCADE, verbose_name='سال', null=True, blank=True) personnel = models.CharField(max_length=150, verbose_name='ثبات', null=True, blank=True) price = models.CharField(max_length=100, verbose_name='مبلغ دریافتی') code_peygiri = models.IntegerField(verbose_name='کد پیگیری', unique=True) date_pardakht = models.DateField(verbose_name='تاریخ پرداخت', null=True, blank=True) bank = models.CharField(max_length=100, verbose_name='بانک', null=True, blank=True) description = models.CharField(max_length=150, verbose_name='توضیحات', blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True) babat = models.CharField(max_length=10, choices=Babat, verbose_name='بابت', null=True, blank=True) def RecivVoucher(request, id): member = get_object_or_404(Profile, pk=id) term = get_object_or_404(Term, termjari=1) form = ReceiveForm() if request.method == 'POST': form = ReceiveForm(request.POST) price = request.POST['price'].replace(",", "") if form.is_valid(): fs = form.save(commit=False) fs.student = member fs.term = term fs.price = price fs.personnel = request.user.id fs.babat = request.POST['babat'] fs.registerleson = request.POST['hazine'] if request.POST['babat'] == 1: fs.registerleson = request.POST['hazine'] if request.POST['babat'] == 2: fs.factor = request.POST['hazine'] fs.save() messages.add_message(request, messages.INFO, 'ثبت با موفقیت انجام شد') redirect('RecivVoucher', id) else: messages.add_message(request, messages.WARNING, 'خطا در ثبت اطلاعات') redirect('RecivVoucher', id) context = { 'member': member, 'form': form, } return render(request, 'member/RecivVoucher.html', context) error : ValueError at /operation/member/RecivVoucher/339/ Cannot assign "'3'": "Receive.registerleson" must be a "Registerleson" instance. -
Programming language selection help. NOOBIES HERE [closed]
Which programming language is good for a startup for creating reddit like social medias, where we can iterate with clean code and learn simultaneously easily. We are looking to learn Python or JS. But what should we choose ? or is there any other language ? -
Is there a way to 'concatenate' a raw sitemap.xml with the generated in django sitemaps?
Django has a built in sitemaps app that create a sitemap.xml, but I need to integrate with another django project that has it's own sitemap.xml. So, the idea it's to make a call to https:another-django-project/sitemap.xml and with that xml 'append' to my django project sitemap.xml and use that as sitemap. There are 2 projects, in different containers, works like one site(one Web, one Wagtail) mysite.com. So, in mysite.com/sitemap.xml should return all info from both I've tried to implement the class WebSitemap(DjangoSitemap): and override something like 'generate_xml()' so I could make a http call to the another application and append the xml, but that doesn't exist. I've tried to make my own view that calls the django sitemaps programmatically, make a call to the another application xml, concatenate and return. doesn't look a good approach. how can I do that? -
VSCode, Django and javascript: Why does VSCode indicate an error when I use {{ }}?
I have the following code that works in my html file: {% for stocks_and_pair_data in stocks_and_pair_data_list %} <script> var ctxClose = document.getElementById('ChartOfClosePrices{{ forloop.counter }}'); new Chart(ctxClose, { type: 'line', data: { labels: {{stocks_and_pair_data.dates|safe}}, datasets: [{ label: '{{ stocks_and_pair_data.stock1_name|safe }}', data: {{stocks_and_pair_data.stock1_close_prices|safe}} },{ label: '{{ stocks_and_pair_data.stock2_name|safe }}', data: {{stocks_and_pair_data.stock2_close_prices|safe}} }] } }); </script> {% endfor %} But VSCode indicates the error "Property assignment expected" at 'labels' line and at both 'data' lines, which are where I use double {{ }} without quotes. I can't use quotes there because these are lists, not strings. Am I doing it wrong, despite of the code working? What should I do to correct it? -
django on update modelform not presenting stored value as selected
I have an uninteresting modelform. One of the model fields, occupation, is a foreignkey to a table containing a long, long list of options. The problem is for update, the rendered form, which is rendered via crispy, does not set focus to the stored value (mark it as the selected option in the <select><option...> code). Instead, it shows the empty choice. I see the initial value does point to the id of the database's record. To make this a little more "interesting," I want to change occupation.to_field_name to occupation.code (a charfield). I've been futzing with the form's init as given below. I can convert the option values to the form I want, but I cannot get the form to present the stored value as selected (and present as the field's selected value). How do I do this? Do I have to do it via JS or am I doing something wrong with the form? Thanks. class Meta: model = TutorOptionalServiceAndDemographics fields = ['highest_degree', 'country_of_birth', 'immigrant', 'us_citizen', 'employment_status_at_enrollment', 'occupation', 'employer_name', 'referral', ] labels = { 'highest_degree': 'Highest degree/diploma earned', 'us_citizen': 'US Citizen:', 'immigrant': 'Immigrant:', 'country_of_birth': 'Country of Birth:', 'employment_status_at_enrollment': 'Employment status at time of registration:', 'occupation': 'Occupation:', 'employer_name': 'Employer Name:', 'referral': … -
how to connect django rest framework with mongodb using pymongo [closed]
how to connect django rest framework with mongodb using pymongo is it possible is it possible to connect django rest framework with mongodb using pymongo. how to connect django rest framework with mongodb using pymongo is it possible is it possible to connect django rest framework with mongodb using pymongo. if isPosible: return "plz msg me" else: return "also plz msg me" -
How to implement in-built scheduled celery tasks in third party packages
I have looked at the celery codebase to get an idea of implementing an in-built scheduled task but I am not sure whether that's the way to go about it for my case. I have a third-party package (meant to be used in Django projects) that needs to have a scheduled in-built celery task, just as backend_cleanup is built in celery. The developer using the package needs to be able to disable the task or update the crontab schedule using some Django settings. This is what I have so far in the package code based on what I saw in the docs: # tasks.py app = Celery() @shared_task def do_stuff(): # do some stuff that will access the database pass @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): okay_to_run = getattr(settings, 'OKAY_TO_RUN', False) if okay_to_run: default_schedule = crontab(0, 0, day_of_month='2') schedule = getattr(settings, 'OKAY_TO_RUN_SCHEDULE', None) if schedule is None: sender.add_periodic_task(default_schedule, do_stuff.s()) else: sender.add_periodic_task(crontab(**schedule), do_stuff.s()) I see celery detects the task but it does not schedule it. What could be wrong and is there a better approach to this? -
How to use design Django APIs using Djoser with multiple users?
I am new to Django and Djoser. I am currently planning to implement a job portal management system. I have 3 stakeholders: companies, recruiters and applicants. So, my company profile is created using official company email and it is used to invite emails that can create an account in my web application as an recruiter, and it will be able to track all the records of the recruiters my recruiter will be able to receive an invitation email that directs them to create an recruiter account, and check on their jobs my applicants will have to create their account on their own In this case while implementing Djoser, I am planning to design the API like the following: # for applicants path('api/', include('djoser.urls')), path('api/', include('djoser.urls.jwt')), # for companies path('api/companies/', include('djoser.urls')), path('api/companies/', include('djoser.urls.jwt')), # for recruiters path('api/recruiters/', include('djoser.urls')), path('api/recruiters/', include('djoser.urls.jwt')), Am I on the right track while designing it like this? Much appreciated if you could describe the pros and cons of doing so (still very new to this). Discussions and feedbacks on how the way I design the APIs. -
How to cancel previous email verifications when django email verification link is sent
After the user changes their email, I get the email activation status wrong and logout, but the user can log back in using the verification from their previous email. To prevent this, I want to cancel all email activation codes that the user previously received when they changed their email. how can I do this? def emailchange(request): if request.method == 'POST': usermail = ProfileAuthSettings(request.POST,instance=request.user) user = MyUser.objects.filter(username = request.user.username).first() if usermail.is_valid(): cleaneddata = usermail.cleaned_data.get('email') print('emial',user.email ,cleaneddata) if not user.email == cleaneddata: user.email = cleaneddata user.is_active = False user.save() asyncio.run(ActiveEmail(request,user)) messages.success(request,'email change') return redirect('/') else: return redirect('login2') else: return redirect('404') @sync_to_async def ActiveEmail(request,creatuser): current_site = get_current_site(request) mail_subject = "accountactivate" message = render_to_string('activate_account.html',{ 'user':creatuser, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(creatuser.pk)), 'token': account_activation_token.make_token(creatuser), }) send_mail(mail_subject, message, settings.EMAIL_HOST_USER, [creatuser.email]) Model class MyUser(AbstractUser): avatar = models.ImageField(("Avatar"), upload_to='avatar/', height_field=None, width_field=None, max_length=None,blank=True,null=True) banner = models.ImageField(("Banner"), upload_to='banner/', height_field=None, width_field=None, max_length=None,blank=True,null=True) rank = models.ManyToManyField(Rank, verbose_name=("Rankı"),blank=True,null=True) birthday = models.DateField(("birthday"), auto_now=False, auto_now_add=False,blank=True,null=True) location = models.CharField(("location"), max_length=50, blank=True,null=True) website = models.CharField(("Website"), max_length=50,blank=True,null=True) about = models.TextField(("about"),blank=True,null=True) likes = models.ManyToManyField("post_app.post", verbose_name=("Beğendiğim postlar"),related_name="mylikes") is_active = models.BooleanField(("email"),default=False) class Meta: verbose_name = 'MyUser' verbose_name_plural = 'MyUsers' def user_profile_detail_url(self): return reverse( 'profile_detail', kwargs={ 'username': self.username } ) from django.contrib.auth.tokens import PasswordResetTokenGenerator import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return( six.text_type(user.pk) … -
Telr payment gateway integration in django
when i done a payment through Telr payment gateway it's response is "status":{"code":-4,"text":"Replaced" }. what is Replaced ? 1 Pending 2 Authorised (Transaction not captured, such as an AUTH transaction or a SALE transaction which has been placed on hold) 3 Paid (Transaction captured, SALE transaction, not placed on hold) -1 Expired -2 Cancelled -3 Declined these are the given responses in Telr documentation. i want to know about responses in Telr gateway and how can i got the paid response? -
Write queryset to seeing in form only teammates of current user
models.py: class Task(models.Model): PRIORITY = [ ("LOW", "Low"), ("MEDIUM", "Medium",), ("HIGH", "High",), ("URGENT", "Urgent",), ("CRITICAL", "Critical",), ] name = models.CharField(max_length=255) description = models.TextField(max_length=1024) deadline = models.DateTimeField() is_completed = models.BooleanField() is_need_help = models.BooleanField() priority = models.CharField( max_length=8, choices=PRIORITY, ) task_type = models.ForeignKey( TaskType, on_delete=models.CASCADE, related_name="tasks" ) assignees = models.ManyToManyField( settings.AUTH_USER_MODEL, ) team = models.ForeignKey( Team, on_delete=models.CASCADE, related_name="tasks" ) is_need_help = models.BooleanField(default=False) class Team(models.Model): name = models.CharField( max_length=255, blank=True, null=True, ) teammates = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="teams", blank=True, ) class Employee(AbstractUser): position = models.ForeignKey( Position, on_delete=models.CASCADE, related_name="employees", null=True, blank=True ) forms.py: class TaskForm(forms.ModelForm): assignees = forms.ModelMultipleChoiceField( queryset=get_user_model().objects.all(), widget=forms.CheckboxSelectMultiple, required=False, ) class Meta: model = Task fields = "__all__" widgets = { "deadline": forms.DateTimeInput(attrs={"type": "datetime-local"}), } views.py: class TaskCreateView(LoginRequiredMixin, generic.CreateView): model = Task form_class = TaskForm I want to create task and assign only for teamates of current user. For exaple - we have two teams: Team1 and Team2, in Team1 two teammates - Tom and Ben, in Team2 also 2 teammates - Catt and Ronnie. Catt can create task only for herself and Ronnie, Ronnie only for himself and Catt. They can't see Tom and Ben in the list of whom to assign task to when they create a new tasks. I hear … -
ModuleNotFoundError: No module named 'real_estate' - uwsgi & django
I've been trying to run my django website using uwsgi, but I keep getting this error. I tried so many solutions from stackoverflow and others but It just doesn't get fixed. I'm using this article to do so: https://medium.com/@panzelva/deploying-django-website-to-vps-with-uwsgi-and-nginx-on-ubuntu-18-04-db9b387ad19d Here are some of the solutions I tried: Having the same version of python in venv and global env(both 3.10.12). Moving wsgi.py file from real_estate directory to the main folder. Changing line 12 of wsgi.py file from "os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'real_estate.settings')" to "os.environ.setdefault['DJANGO_SETTINGS_MODULE']= 'real_estate.settings'" or "os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')" I tried running my website like this: "vim uwsgi/sites/real_estate.ini" and then opened my browser tab to this <my_vps_ip_address>:8000, but I get This: "Internal Server Error" and this in my error log: Here's my uwsgi .ini file: Also tried this way: -
Issue with using python-decouple in Django project
I have an issue getting python-decouple to work in my Django project. My .env file located in what BASE_DIR in settings.py resolves to: SECRET_KEY=ARANDOMSECRETKEY My settings.py: from pathlib import Path import locale from decouple import config # config.encoding = locale.getpreferredencoding(False) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') If I start my django project with the config.encoding line commented out, it errors out with: File "<frozen codecs>", line 322, in decode UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte If I start my project with that line, different error: Lib\site-packages\decouple.py", line 92, in get raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: SECRET_KEY not found. Declare it as envvar or define a default value. I've added the .env file in pretty much every path available now, no luck :( I've also tried to work with a settings.ini file instead: [settings] SECRET_KEY=ARANDOMSECRETKEY This errors out with: configparser.MissingSectionHeaderError: File contains no section headers. file: 'xxxx\\settings.ini', line: 1 'ÿþ[\x00s\x00e\x00t\x00t\x00i\x00n\x00g\x00s\x00]\x00\n' While if I rename the settings.ini file into settings.old, error changes into SECRET_KEY … -
How to address N+1 problem in django with prefetch related?
With the following code I am getting N numbers of queries based on the loop. How to avoid that ? I tried using prefetch_related but that didn't worked or am i doing the wrong way ? models class Product(models.Model): name = models.CharField() .... class ProdcutOffer(models.Model): product = models.ForeignKey(Product, related_name="offers") .... def my_view(request): qs = Product.objects.filter(is_active=True).prefetch_related("offers") data = [] for product in qs: data.append( { ...., "offer":product.offers.filter(is_active=True, is_archived=False).last() } ) paginator = Paginator(data, 10) try: page_obj = paginator.page(page_num) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) return page_obj -
Using tests.py file with apps in a root directory
I have a small project with all the apps inside a root directory named apps. Everything works fine, but now I tried to add some tests in the tests.py class CursoModelTests(TestCase): def test_two_identical_slugs(self): curso1 = Curso( nombre='Curso 1', precio=10, descripcion_breve='Hola', slug='prueba', profesor=create_profesor() ) with self.assertRaises(IntegrityError): Curso( nombre='Curso 2', precio=20, descripcion_breve='Otro curso', slug='prueba', profesor=create_profesor() ) And when I run python manage.py test apps I get this error System check identified no issues (0 silenced). E ====================================================================== ERROR: curso.tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: curso.tests Traceback (most recent call last): File "C:\Users\Usuario\AppData\Local\Programs\Python\Python38\lib\unittest\loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "C:\Users\Usuario\AppData\Local\Programs\Python\Python38\lib\unittest\loader.py", line 377, in _get_module_from_name __import__(name) File "C:\Users\Usuario\Desktop\Apps creadas\cocina-salud\CocinaSalud\apps\curso\tests.py", line 5, in <module> from .models import Curso File "C:\Users\Usuario\Desktop\Apps creadas\cocina-salud\CocinaSalud\apps\curso\models.py", line 7, in <module> class Curso(BaseModel): File "C:\Users\Usuario\Desktop\Apps creadas\cocina-salud\venv\lib\site-packages\django\db\models\base.py", line 132, in __new__ raise RuntimeError( RuntimeError: Model class curso.models.Curso doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. ---------------------------------------------------------------------- Ran 1 test in 0.000s When I define an app_label in the Meta class this way class Curso(BaseModel): # fields... class Meta: app_label = 'apps.curso' I receive this other error Found 1 test(s). System check identified no issues (0 silenced). E ====================================================================== ERROR: curso.tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: … -
Designing a Generic List Manager Library with User Permissions in Django/Python
I'm currently in the process of developing a versatile and reusable Generic List Manager Library for applications built with Django/Python. This library aims to provide a generic solution for creating and managing lists of various entities Here are the key requirements for this generic library: User-List Association: A list should be associated with one or multiple users. User Permissions: Users linked to a list should have different permissions such as read, write, and share rights. Abstract Lists: Lists should be abstract and capable of linking to a single model, with a field defining the primary model it references. Multiple Models: It should be possible for two different lists to point to different models. I am seeking advice on what are some suitable design patterns for doing this. I am thinking of using a combination between Repository Pattern && Mediator Pattern to implement this, but I would love to hear different opinion or takes into this. -
I am unable to update value of lifecycle stage using hubspot api
I am using hubspot api to update the value of lifecycle stage of a contact. The value can be changed to any other value in the hubspot crm. But when I am using the api to do so, I can change the value of the lifecycle stage to a higher stage say, from a Subscriber to Lead, as Subscriber is lower in rank than Lead. But when I try to change the value from Lead to Subscriber using the api, it doesn't do so. There is no error too. I am not sure if it is a bug with the api or there is some restriction to do so. The code for my api: def update_contact_lifecycle_stage(request , *args): try: api_client = HubSpot(access_token=HUBSPOT_API_KEY) #get this from params contact_email = "test@test.com" filter_query = { "propertyName": 'email', "operator": 'EQ', "value": contact_email } filterGroup = { "filters" : [filter_query] } search_request = PublicObjectSearchRequest( filter_groups= [filterGroup], properties=['vid'] ) response = api_client.crm.contacts.search_api.do_search(public_object_search_request=search_request) contacts = response.results if contacts: contact_vid = str(contacts[0].id) #Get this from params new_lifecycle_stage = "subscriber" contact_update = { "lifecyclestage": new_lifecycle_stage } simple_public_object_input = SimplePublicObjectInput( properties=contact_update) try: api_response = api_client.crm.contacts.basic_api.update( contact_vid, simple_public_object_input=simple_public_object_input ) except ApiException as e: print(f"HubSpot API error: {e}") except Exception as e: … -
I cannot get my site to show on a reverse proxy NginX server
I am trying to deploy a Django website on a VPS and I have everything set up in terms of the following: The app runs if I use the development server and I go to xxx.xxx.xxx.xxx:8000 Nginx is running because if I go to the site at founderslooking.com I can see the nginx server page. I am following the instructions from a video as this is my first time doing it and I have set up supervisor. I have the following conf file set up so I can use nginx as a reverse proxy but clearly this is not working because I do not see my site. I checked and supervisor is running. /etc/nginx/sites-available/founders.conf: upstream founders_app_server { server unix:/websapps/founders/founders_3_10_12/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name api.founderslooking.com; client_max_body_size 4G; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename){ proxy_pass http://founders_app_server; } } } If I change the server name to founderslooking.com then I get a bad gateway if I go to founderslooking.com /etc/supervisor/conf.d/founders.conf: [program:founders] command = /webapps/founders/founders_3_10_12/bin/gunicorn_start user = userfounders stdout_logfile = /webapps/founders/founders_3_10_12/logs/supervisor.log redirect_stderr = true environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 Not sure what else to include here but I checked and nginx is running, supervisor is running and … -
Django Permission per Database Object
I have an architectural question regarding Djangos permission model. I do have a Database Model which hold companies, and each company can have multiple projects. Users should be able to only see companies that they are assigned to and only see projects which they are assigned to. I am now confused whether I should have a Many2Many Relation in the companies and projects which holds the allowed users and then check them on access through the permission system? Or create a new permission for each company, add this permission to the company and/or project and then give the users these permissions? Somehow I think solution 1. gets me into problems in the long run when querying all projects one user should see. But solutions 2 got me stuck since there is no permission field in the models, so I always have to cast string field to permission and I will generate a huge amount of permissions overall. Maybe I am completely overthinking this? What would be the best approach to per Database-Entry permissions? Thanks and Best Regards -
Django-admin: how to make save_formset() work once with a few inlines?
My admin.py: class PollMediaInline(admin.StackedInline): model = PollMedia extra = 1 # Количество дополнительных полей для добавления readonly_fields = ('absolute_media_path',) class PollOptionsInline(admin.StackedInline): model = PollOptions extra = 1 # Количество дополнительных полей для добавления @admin.register(Poll) class BotUserAdmin(admin.ModelAdmin): list_display = ('id', 'user', 'title', 'group', 'approved', 'created_at') list_filter = ('created_at', 'approved', 'group') search_fields = ('title', 'approved') ordering = ('approved',) readonly_fields=('user',) inlines = [PollOptionsInline, PollMediaInline] def save_model(self, request, obj, form, change): pass # don't actually save the parent instance def save_formset(self, request, form, formset, change): formset.save() # this will save the children form.instance.save() # form.instance is the parent signals.py: @receiver(post_save, sender=Poll) def post_without_media_created(sender, created, instance, **kwargs): send_poll_sync = async_to_sync(send_poll) print(", ".join([option.option for option in instance.options.all()]), instance.title, ", ".join([media.absolute_media_path for media in instance.mediafiles.all()]), sep='\n') send_poll_sync([option.option for option in instance.options.all()], instance.title, [media.absolute_media_path for media in instance.mediafiles.all()]) models.py: class Poll(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Менеджер') scheduled_time = models.DateTimeField(blank=True, null=True, verbose_name="Дата и время рассылки") title = models.CharField(max_length=200, verbose_name='Заголовок') # options = models.TextField(verbose_name='Варианты ответа') # correct_answer = models.PositiveIntegerField(blank=True, null=True, verbose_name='Правильный ответ(если пусто, то без правильных ответов)') approved = models.BooleanField(default=False, verbose_name='Подтверждён') # total_media_count = models.PositiveIntegerField(default=0, verbose_name='Сколько фотографий загрузите?') group = models.ForeignKey('bot_users.BotUserGroup', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Группа пользователей бота') created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True, verbose_name='Создано') def save(self, *args, **kwargs): if … -
Django cannot send email with gmail smtp using Docker, working without docker
I developed a Django app that sends verification code via email. When I run the code locally using like PyCharm my code works and emails are being sent. Then I wanted to contenerize my application using Docker. I did, but everything works beside the sending email. I get the following error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1002) when executing email.send(). I use private network at home. Port 587 is not blocked. This is my DockerFile FROM python:3.11.4-slim-buster # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install system dependencies RUN apt-get update \ && apt-get -y install libpq-dev gcc \ && pip install psycopg2 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy main.sh COPY ./main.sh . RUN sed -i 's/\r$//g' /usr/src/app/main.sh RUN chmod +x /usr/src/app/main.sh # copy project COPY . . # run main.sh ENTRYPOINT ["/usr/src/app/main.sh"] This is the docker-compose.yml version: '3.9' services: backend: build: context: ./backend command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 - 587:587 volumes: - ./backend/:/usr/src/app/ environment: - DB_NAME=db_name - DB_USER=db_user - DB_PASSWORD=db_pass - DB_HOST=db - DB_PORT=5432 - EMAIL_USE_TLS=True - EMAIL_FROM=email@gmail.com - … -
Django model datetime filter ( model.objects.filter(datetime_field__lt=datetime.now()) ) is not work
I try to filter my data model in model view.py with a datetime field. But it filter total data records and none of data is in result! And how to filter datetime fields with 'None' value? Please help me to resolve this issue problem. which part of model data filed definition is: class Post(models.Model): title = models.CharField(max_length=200,verbose_name="Título") content = models.TextField() counted_views = models.IntegerField(default=0) published_date = models.DateTimeField(blank=True, null=True) ... my command statement: posts = Post.objects.filter(published_date__lt=datetime.now()) -
Nginx, ReactJS with Django Architecture
I'm new to this technology. Can anyone explain how the Architecture works ?. Where the user request will hit first, to Nginx or React or Django. How to implement a great Architecture ?. What are the good APIs use in between for better performance.