Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Operation of standard Django view, form and template code to update a model
I am trying to understand how a very regularly used code-form in Django views.py actually works. I see the following (or a variation) used a lot, but I can’t find a line-by-line explanation of how the code works – which I need if I am to use it confidently and modify when needed. I will start with the model then introduce urls.py the view and the form. I will go through the relevant parts of the code. I will consider: The model: #models.py class CC_Questions(models.Model): # defining choices in Model : https://docs.djangoproject.com/en/4.0/ref/models/fields/ personality = [ ('IF','IF'), ('IT','IT'), ('EF','EF'), ('ET','ET'), ] q_text = models.CharField('Question text', max_length=200) #C1_Type = models.CharField('Choice 1 Type', max_length=2) C1_Type = models.CharField(choices=personality, max_length=2) Choice1_text = models.CharField('Choice 1 text', max_length=100) #C2_Type = models.CharField('Choice 2 Type', max_length=2) C2_Type = models.CharField(choices=personality, max_length=2) Choice2_text = models.CharField('Choice 2 text', max_length=100) # def __str__(self): return self.q_text[:20] The url # #urls.py app_name = ‘polls’ urlpatterns = [ ….. # ex: /polls/p2create path('p2create/', p2_views.p2create, name='p2create'), … The view: #views.py from.forms import Anyform # def p2create(request): if request.method == 'POST': form = AnyForm(request.POST) if form.is_valid(): form.save() return redirect('/polls/p2') else: form = AnyForm() context = {'form' : form} return render(request, 'pollapp2/create.html', context) # The form: #forms.py # …. … -
How to show foreign key strings related value in Django Rest Framework
I get responses in foreign key values as shown below image Image is here but I want the response of values in string which Is returned from str method in models file. my models is given below from django.db import models from django.contrib.auth.models import AbstractUser,AbstractBaseUser from .Manager import Custom_Manager # Create your models here. class user_profile(AbstractUser): username = None first_name = models.CharField(max_length=250,blank=True,default='') last_name = models.CharField(max_length=250,blank=True,null=True,default='') email = models.EmailField(verbose_name='email_address', max_length=255, unique=True) address=models.CharField(max_length=250) profile_picture=models.ImageField(upload_to='Profile Pictures', blank=True) objects = Custom_Manager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email; class Category(models.Model): name=models.CharField(max_length=250,null=True,blank=True) def __str__(self): return self.name; class Services(models.Model): s_name=models.CharField(max_length=255) provider_user=models.ForeignKey('digi_khidmat.user_profile',on_delete=models.CASCADE) category=models.ForeignKey(to='digi_khidmat.Category',on_delete=models.CASCADE ,blank=True,null=True) Services_image=models.ImageField(upload_to='Services', blank=True,null=True) description=models.CharField(max_length=1000,blank=True) services_rate_per_hour=models.IntegerField() def __str__(self): return self.s_name class request_services(models.Model): services = models.ForeignKey(to='digi_khidmat.Services', on_delete=models.CASCADE,related_name="Services") provider_user = models.ForeignKey(to='digi_khidmat.user_profile', on_delete=models.CASCADE,related_name="service_provider") category = models.ForeignKey(to='digi_khidmat.Category', on_delete=models.CASCADE, blank=True, null=True ) request_user = models.ForeignKey(to='digi_khidmat.user_profile', on_delete=models.CASCADE,related_name="request_user") status=models.ForeignKey(to='digi_khidmat.services_status', on_delete=models.CASCADE,related_name="request_user") class services_status(models.Model): status=models.CharField(max_length=10,default='Pending') def __str__(self): return self.status; my Serializer class is below class user_profile_serializer(serializers.ModelSerializer): class Meta: model=user_profile fields='__all__' class Category_serializer(serializers.ModelSerializer): class Meta: model=Category fields='__all__' class Services_serializer(serializers.ModelSerializer): class Meta: model=Services fields='__all__' class Services_status(serializers.ModelSerializer): class Meta: model=services_status fields='__all__' class request_services_serializer(serializers.ModelSerializer): serviese_name=serializers.StringRelatedField(read_only=True) class Meta: model=request_services fields='__all__' when i convert serviese_name=serializers.StringRelatedField(read_only=True) to serviese_name=serializers.StringRelatedField(read_only=True, many=True) it throws the following error ceback (most recent call last): File "C:\Users\Muhammad Arshad\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = … -
How to write class based testview for Django Channels using unittest module
I am trying to write unittests for my web sockets. I haven't wrote any previously so I am struggling understanding how to write using module unittest python package. This is my consumer: class DepartmentInfoConsumer(JsonWebsocketConsumer): def connect(self): if not self.scope["user"]: raise DenyConnection() self.accept() self.group_name = "test" async_to_sync(self.channel_layer.group_add)(f"department{self.scope['company'].id}", self.channel_name) departmentobject = Department.objects.get(company=self.scope["company"]) self.send_json({"used_id": departmentobject.my_id}) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)(f"department{self.scope['company'].id}", self.channel_name) raise StopConsumer() def used_id_info(self, event): self.send_json({"used_id": event["used_id"]}) MY URL: websocket_urlpatterns = [ re_path("bill/", consumers. DepartmentInfoConsumer.as_asgi(), name="billing-ws"), ] -
django error with postgresql database on real host
this is my first python programe to run on server and i have error in database connection. when i add this line to setting file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'rahepooy_afsoone_db', 'USER': 'rahepooy_afsoone', 'PASSWORD': '****************', } } and migrate the code i have error : psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? if i add "hoset':'IP' to setting.py i have this error : psycopg2.errors.UndefinedColumn: column c.relispartition does not exist LINE 3: CASE WHEN c.relispartition THEN 'p' WHEN c.relki... where is my mistake!? and this project is on real host on internet -
Can anyone help me,when i send mail through django send mail i am getting errors,if i send mail without deploy then it working [closed]
but if i send without deploy , it's working 1: enter image description herehttps://i.stack.imgur.com/AhOTz.jpg*emphasized text* -
I want to print my data on html that is stored in excel sheet(xlsx), actually i am getting output but it is not in a proper way . please check code
Views.py info = [] def get_info(request): r1 = pd.read_excel('file_data.xlsx') for index, row in r1.iterrows(): if row["USER NAME"] == str(user_name()): info.append(row) #name = row['USER NAME'] #date = row['DATE'] #file_name = row['FILE NAME'] #remarks = row['REMARKS'] return render(request,'files.html',{'info':info}) #return render(request,'files.html',{'name':name, 'date':date, 'file_name':file_name, 'remarks':remarks, 'info':info}) output enter image description here I need to print data in corresponding fields but it coming only in single field in list format. -
What queryset should I do to select all One-to-one relations that are broken?
I have this 2 models : class Asset(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) ... some other fields ... class AssetConstructorData(models.Model): asset = models.OneToOneField( Asset, on_delete=models.CASCADE, primary_key=True, related_name='constructor_data', ) ... some other fields ... For some historical reason, I have some One-to-one which are broken : some AssetConstructorData object has not their corresponding Asset object. I would like to delete all AssetConstructorData objects that are broken. Actually I have done : for cd in AssetConstructorData.objects.all(): try: cd.asset except Asset.DoesNotExist: cd.delete() Which is definitively not optimized : Is that possible to make a queryset that selects all broken relations ? I tried with .filter(asset=None) and .filter(asset__isnull=True) but it does not work. -
Getting issue while edit record in Django Form
I Everyone i am getting issue while edit record based on problem id, only problem record show automatically chatquestion and option record not show automatically, maybe my ORM is wrong somewhere, please help me out. this is crud operation i have done list and add record but that is also complex if anyone can do simple its more helpful for me.. Thanyou. models.py -this is all 3 models. class Problem(models.Model): Language = models.IntegerField(choices=Language_CHOICE, default=1) type = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return self.type class ChatQuestion(models.Model): question = RichTextField(null=True, blank=True) problem_id = models.ForeignKey( Problem, models.CASCADE, verbose_name='Problem', ) sub_problem_id = models.ForeignKey( SubProblem, models.CASCADE, verbose_name='Sub Problem', null=True, blank=True ) def __str__(self): return self.question class Option(models.Model): option_type = models.CharField(max_length=250, null=True, blank=True) question_id = models.ForeignKey( ChatQuestion, models.CASCADE, verbose_name='Question', ) problem=models.ForeignKey( Problem, models.CASCADE, verbose_name='Problem', null=True, blank=True ) next_question_id = models.ForeignKey(ChatQuestion, on_delete=models.CASCADE, null=True, blank=True, related_name='next_question') forms.py class Editchatbot(forms.Form): problem=forms.ModelChoiceField(queryset=Problem.objects.all(), required=True, widget=forms.Select(attrs={'class': 'form-control select2'})) question=forms.ModelChoiceField(queryset=ChatQuestion.objects.all(), required=True, widget=forms.Select(attrs={'class': 'form-control select2'})) option=forms.ModelChoiceField(queryset=Option.objects.all(), required=True, widget=forms.Select(attrs={'class': 'form-control select2'})) class Meta: fields=['problem','question','option'] views.py def edit_chatbot(request,id=None): problem=Problem.objects.get(pk=id) question=ChatQuestion.objects.filter(problem_id=id) option=Option.objects.filter(question_id=id) if request.method == 'POST': form = Editchatbot(request.POST) if form.is_valid(): problem=form.changed_data['problem'] question=form.changed_data['question'] option=form.changed_data['option'] form.save() messages.success(request,'successfully!') return redirect('/fleet/chatbot_list') else: messages.error(request,'Please correct following',form.errors) else: form = Editchatbot(initial={'problem':problem,'question':question,'option':option}) context = { 'menu_management': 'active', 'chatbot': 'active', 'form': form, 'question':question, 'option':option … -
Python pipenv failts to install libraries?
My pipenv environment refuses to install various python libraries, citing a problem with the ssl certificate, any solutions out there? Here is the error message: PS C:\Users\NAME\OneDrive\Documents\GitHub\mainsite> pipenv install django Installing django... Error: An error occurred while installing django! Error text: Could not fetch URL https://pypi.org/simple/django/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/django/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after … -
Django-Tenants causes App_model does not exist with functional pytest
I have been trying to do this using functional test approach not class test class based approach: class SomeTest(TenantTestCase): def setup(): super().setup() def test_some_do_something(): #... test_code def test_some_do_something_again(): #... test_code_again The above class based approach works well since it can easily create a tenant based on TenantTestCase but then when try to replicate the above in normal functions., I face difficulties , another reason is I am using pytest for my test and pytest works better with Normal Functional test approach than Class test approach Function approach: def test_some_thing_using_functional_test_approach(): # .. some assertion code #The above causes error the app_model relation does not not exist . This is because they live in schemas and therefore how do I ensure the tenant is created first and accessed in a functional test approach to avoid this issue -
How to use model functions in Views for multiple instances in Django?
I have a Blog Post Model and I have defined a function to calculate the no of likes. The Model is as follows -> class Post(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) title = models.CharField(max_length=255) description = models.CharField(max_length=1000,null=True) Tags = models.CharField(max_length = 255,null=True,blank=True) Created_date = models.DateTimeField(auto_now_add=True) Updated_date = models.DateTimeField(auto_now=True) category = models.ForeignKey(Category, on_delete=models.PROTECT) Likes = models.ManyToManyField(to=User, related_name='Post_likes') def __str__(self): return self.title def likesCount(self): return self.Likes.count() Now I am querying the Post Model from the DB to get all the Posts as follows -> posts = Post.objects.select_related().prefetch_related('images_set','comments_post').annotate(Count('comments_post')).all() Here when I loop over the posts I can call the likesCount function and it gives me the correct result as well but I want to return the No of likes to the template. How can I do that? -
React vs Django : Which framework shall I learn
I am front end developer[React]. I also want to learn the backend. I am confused due to contradictory statement in different blogs etc. Some says that node may be out of date after some time. So says node is better to learn than Django. Can someone help me by providing the authentic information. So learn the framework. Thanks in advance. -
How add 0 when TruncWeek's week no result in Django Query?
I want query the issue's count of group by weekly. query1 = MyModel.object.filter(issue_creator__in=group.user_set.all()).\ annotate(week=TruncWeek('issue_creat_date')).values('week').annotate(count=Count('id')).order_by('week')) the query result is OK. the queryset result: [ {'week': datetime.datetime(2022, 1, 3, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'count': 9}, {'week': datetime.datetime(2022, 1, 10, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'count': 12}, {'week': datetime.datetime(2022, 1, 17, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'count': 10}, {'week': datetime.datetime(2022, 2, 7, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'count': 1}, {'week': datetime.datetime(2022, 2, 14, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'count': 6}, {'week': datetime.datetime(2022, 2, 21, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'count': 11}, {'week': datetime.datetime(2022, 2, 28, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'count': 1} ] but 20220101-20220301 has 9 weeks: [ datetime.datetime(2022, 1, 3, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 1, 10, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 1, 17, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 1, 24, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 1, 31, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 2, 7, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 2, 14, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 2, 21, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), datetime.datetime(2022, 2, 28, 0, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>) ] I want add zero … -
get multiple times or filter id__in on a queryset which is more efficient in django?
Which of the following is more efficient in django? items = [item for item in queryset.filter(id__in=ids)] items = [queryset.get(id=id) for id in ids] -
what is difference between these two
I have checkboxes in my view for filtering the data i have two different fileds implemented like this in my ListAPIView what's the difference between field 1 and field_2 field_1 = request.GET.get('field_1', 'true') == 'true' field_2 = request.GET.get('field_1', False) -
How to get .env to pre-commit + mypy + django-stubs
I try to configurate start mypy + django-stubs cheking before commiting. I use pre-commit for it. When I try to commit, I have error django.core.exceptions.ImproperlyConfigured: Set the POSTGRES_DB environment variable. This variable is in .env file, I export variables from .env to Django config using django-environ. And of course .env in .gitignore. So, as far as I understand: pre-commit starts with its own virtual environment, and it doesn't know about my .env file. Above all, do I correct to understand my situation? If I'm right, how to get variables from .env file to pre-commit enviroment? My .pre-commit-config.yaml (part) - repo: https://github.com/pre-commit/mirrors-mypy rev: '' hooks: - id: mypy exclude: "[a-zA-Z]*/(migrations)/(.)*" args: [--config=setup.cfg, --no-strict-optional, --ignore-missing-imports] additional_dependencies: [django-stubs, django-environ] my setup.cfg [mypy] python_version = 3.9 allow_redefinition = True check_untyped_defs = True ignore_missing_imports = True incremental = True strict_optional = True show_traceback = True warn_no_return = False warn_unused_ignores = True warn_redundant_casts = True warn_unused_configs = True plugins = mypy_django_plugin.main show_column_numbers = True [mypy.plugins.django-stubs] django_settings_module = config.settings.local [mypy_django_plugin] ignore_missing_model_attributes = True [mypy-*.migrations.*] # Django migrations should not produce any errors: ignore_errors = True -
(django_mysql.E016) MySQL 5.7+ is required to use JSONField
I am getting following error: (django_mysql.E016) MySQL 5.7+ is required to use JSONField HINT: At least one of your DB connections should be to MySQL 5.7+ My current MySQL version is 5.7.37 mysql Ver 14.14 Distrib 5.7.37, for Linux (x86_64) using EditLine wrapper my Django version is: 2.2.16 my Django-mysql version is: 3.2.0 Can someone let me know what is the issue? -
How do I redirect from a view to a root URL in Django?
I'm trying to add a link to my django site that redirects from the catalog1 view to the catalog2 page. So basically, I want to go from .../catalog1 to .../catalog2/other-page. All the other answers that I've seen require redirecting to http://127.0.0.1:8000/ first, and then redirecting to catalog2, but I've set up the site so that http://127.0.0.1:8000/ automatically redirects to catalog1, so this isn't working. Any help would be appreciated. Thanks, FluffyGhost -
Apache can't return secrets from AWS secrets manager
How do I set apache to run aws configure before running my application? ERROR LOG : [Tue Mar 01 04:30:32.202853 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "/home/ubuntu/env/lib/python3.8/site-packages/django/conf/init.py", line 71, in _setup [Tue Mar 01 04:30:32.202857 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] self._wrapped = Settings(settings_module) [Tue Mar 01 04:30:32.202867 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "/home/ubuntu/env/lib/python3.8/site-packages/django/conf/init.py", line 179, in init [Tue Mar 01 04:30:32.202872 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] mod = importlib.import_module(self.SETTINGS_MODULE) [Tue Mar 01 04:30:32.202882 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "/usr/lib/python3.8/importlib/init.py", line 127, in import_module [Tue Mar 01 04:30:32.202898 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] return _bootstrap._gcd_import(name[level:], package, level) [Tue Mar 01 04:30:32.202910 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "", line 1014, in _gcd_import [Tue Mar 01 04:30:32.202921 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "", line 991, in _find_and_load [Tue Mar 01 04:30:32.202931 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "", line 975, in _find_and_load_unlocked [Tue Mar 01 04:30:32.202942 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "", line 671, in _load_unlocked [Tue Mar 01 04:30:32.202952 2022] [wsgi:error] [pid 54523:tid 139982691088128] [remote 68.234.152.211:50306] File "", line 848, in exec_module [Tue Mar 01 04:30:32.202963 2022] … -
django dynamic forms setting max_length property
I am creating a 'Forms Management' system for my application. I am creating a forms dynamically using a custom form 'factory' method. Form data is in a json file. I can create a forms.CharField and set the label, required, initial and help_text properties. When I try to set the max_length property I do not get any error message, but the resulting HTML does not contain the max_length attribute. In static forms defined as class SearchAccountForm(forms.Form): provider_code = forms.CharField( label='Provider:', max_length=100, required=True, widget=forms.TextInput(attrs={'class': 'form-control'})) The resulting HTML contains the max_length attribute. <label for="id_provider_code">Provider:</label> </th><td><input type="text" name="provider_code" class="form-control" maxlength="100" required id="id_provider_code"> So what's up with max_length?? Json file { "form1": [ { "fld_name": "customer_name", "fld_type": "CharField", "fld_label": "Cust Name", "fld_required": "False", "fld_maxLength": 5, "initial": "Dr John" }, { "fld_name": "customer_number", "fld_type": "CharField", "fld_label": "Cust #", "fld_required": "True", "fld_maxLength": 15, "help_text": "Enter account number" }, { "fld_name": "customer_type", "fld_type": "CharField", "fld_label": "Customer Type", "fld_required": "False" } ] } and the forms.py factory method from django import forms import json def dynfrm(): f = open('blog/frmJson/frm1.json') data = json.load(f) fields = {} for i in data['form1']: ## form1 = form name in json file print(i) ## add to fields list if i['fld_type'] == 'CharField': fields[i["fld_name"]] … -
How to fix ERROR: Failed building wheel for psycopg2?
I am using ubuntu 20.04 and want to install django project dependencies using requirements.txt file. The project is using python3.9. and I've installed python3.9 and postgresql already. I already tried to install dependencies using pipfile, but it failed locking dependencies. installing dependencies give this error: Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-fu9m38m8/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-fu9m38m8/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-rqzwqrsw cwd: /tmp/pip-install-fu9m38m8/psycopg2/ Complete output (38 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.8 creating build/lib.linux-x86_64-3.8/psycopg2 copying lib/sql.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_range.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/pool.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/errors.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_ipaddress.py -> build/lib.linux-x86_64-3.8/psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build/temp.linux-x86_64-3.8 creating build/temp.linux-x86_64-3.8/psycopg x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -DPSYCOPG_VERSION=2.9.1 (dt dec pq3 ext lo64) -DPSYCOPG_DEBUG=1 -DPG_VERSION_NUM=120009 -DHAVE_LO64=1 -DPSYCOPG_DEBUG=1 -I/usr/include/python3.8 -I. -I/usr/include/postgresql -I/usr/include/postgresql/12/server -I/usr/include/libxml2 -I/usr/include/mit-krb5 -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-3.8/psycopg/psycopgmodule.o … -
How to get class values in static method
I want to get the field value like we use self in Django models. class UserModel(Model): id = IDField() uid = TextField() @classmethod def get_user(cls): return cls.uid The class method, keep returning NONE instead of the string value of the uid field. Did I miss something? This is from the Firestore Python wrapper https://octabyte.io/FireO/quick-start/ -
No module named 'guardian.backends'?
i am deploying a django project, the uwsgi & nginx & mysql are already set, and the 127.0.0.1:8000 url went well, but occured an ModuleNotFoundError when i went into the 127.0.0.1:8000/admin url, it's like: ModuleNotFoundError: No module named 'guardian.backends' i don't understand this error. -
Finding the nearest observation station from National Weather Service API in Python/Django
So after finding the coordinates for the closest station, I need to extract the name of the station. This is an example of the response I'm working with: https://api.weather.gov/gridpoints/OKX/34,39/stations The station data is in the 'features' property. How do I go about extracting the name of the station based on the coordinates. -
Apscheduler stopped working randomly without any exception
I build a django webset and use apscheduler to do some scheduled tasks. Everything was alright at startup. But after some time, the scheduler refused to work and left nothing in log. The log just stopped without exception. Below is the framework of how I run the scheduler: from rpyc.utils.server import ThreadedServer class Command(BaseCommand): help = "Runs apscheduler." def handle(self, *args, **options): scheduler = BackgroundScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.start() server = ThreadedServer(SchedulerService(scheduler), port=settings.MY_RPC_PORT, protocol_config=protocol_config) try: # logging.info("Starting thread server...") server.start() except (KeyboardInterrupt, SystemExit): pass finally: scheduler.shutdown() And here are the dependencies: dependencies: - python=3.8.3=hcff3b4d_2 - apscheduler=3.6.3=py38_1 - django=3.2=pyhd3eb1b0_0 - pip: - django-apscheduler==0.6.0 - rpyc==5.0.1 What's more, while apscheduler was refusing to work, the rpyc server could still be connected and leave message in log. Can anyone help me to figure out what was wrong here? You have my gratitude.