Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run python script with multiple users accessing Django server
I have built a python script to run some process in downloading files and serve to users, I also built a website and added it to the Django framework, Now it is working properly for a single users (tested in the development environment, not a production environment). For example, If one user is using the website to request a particular file the background script runs properly and completes the task, and make files on the server... but if multiple users try to input the file at the same time, the backend python code is run but the Django produces an error. Is there a way that each individual user will have a separate instance of the script running for them without interrupting the process of other users? In views.py file : def index(request): if(request.method == "POST"): # here I call the function of other python files to run the script # the process may take like 15 - 30 sec based on internet speed # return a FileResponce of the file to be served to the user -
How to restore default celery backend_cleanup task in django?
I'm using Django celery-beat with a Redis backend. I accidentally deleted the celery.backend_cleanup Crontabschedule, which deleted the Periodic task that was using it. How do I put them back? From the celery docs: result_expires Default: Expire after 1 day. Time (in seconds, or a timedelta object) for when after stored task tombstones will be deleted. A built-in periodic task will delete the results after this time (celery.backend_cleanup), assuming that celery beat is enabled. The task runs daily at 4am. A value of None or 0 means results will never expire (depending on backend specifications). -
I am getting an Integrity Error django rest framework?
enter image description here i am getting an error of UNIQUE constraint failed: auth_user.username myuser = User.objects.create_user(username, email, pass1) -
Django models choice textField mapping
I am building a website for myself I am updating my projects from django admin I wanted to create a custom field which is a map of choice(tag color) and tag text. I want to make it look something like this This is my model class Project(models.Model): projectTemplate = CloudinaryField('image') projectTitle = models.TextField(default="Title ") desc = models.TextField(default="not mentioned") projectLink = models.URLField(max_length=200, default="not mentioned") created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.projectTitle} - {self.desc[:15]} ..' views.py def projects(request): Projects = Project.objects.all() return render(request, 'devpage/projects.html',{'Projects': Projects}) This is my current DTL {% for project in Projects %} <div class="col"> <div class="card shadow-sm"> <img src="{{ project.projectTemplate.url }}" height="225" width="100%"> <div class="card-body"> <h6 class="text-center"> {{ project.projectTitle }} </h6> <p class="card-text">{{ project.desc }}</p> <div class="mb-3"> <span class="badge rounded-pill bg-secondary">Django</span> <span class="badge rounded-pill bg-success">Python</span> </div> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <button type="button" class="btn btn-sm btn-warning btn-outline-secondary"><a href="{{ project.projectLink }}" target="_blank" type="button" class="btn">View</a></button> </div> <small class="text-muted">{{ project.created_at }}</small> </div> </div> </div> </div> {% endfor %} I want a custom model field which takes choice of label color and corresponding text with dynamic size I tried using json(field name tags) but its not interactive This is JSON DTL //Inner for loop for tags <div class="mb-3"> {% for color,text … -
Django, Html: How i can display the (number of page / total pages exist) on a pdf printout rendered
I have render an html template to pdf as response working with the framework Django and i want to add a footer contain the number of page in the pdf-printout / total number of pages for example if i have 2 pages in total , the first page should display to me 1/2, How i can do that please using html! I have tried with this code : <footer> {%block page_foot%} <div style="display: block;margin: 0 auto;text-align: center;"> page: <pdf:pagenumber /> </div> {%endblock%} </footer> But it display 0 as a first page. Thanks in advance -
Django Next.js handling responses when signing up
I am building my first Django + Next.js app and I want to display an alert when the user sign up if the username or the email already exists. Currently, if the user chooses an username/email that already exists there is a 400 error (what I want), otherwise everything is working fine. When I try it on postman, I get the explicit problem (username already exists or email already exists). But I didn't manage to achieve that on my frontend, even in the console, I don't see any message. RegisterView : class RegisterView(APIView): permission_classes = (permissions.AllowAny, ) def post(self, request): try: data = request.data email = data['email'] username = data['username'] password = data['password'] re_password = data['re_password'] if password == re_password: if len(password) >= 8: if not User.objects.filter(username=username).exists(): if not User.objects.filter(email=email).exists(): user = User.objects.create_user( email=email, username=username, password=password, ) user.save() if User.objects.filter(username=username).exists(): return Response( {'message': 'Account created successfully'}, status=status.HTTP_201_CREATED) else: return Response( {'message': 'Something went wrong when trying to create account'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: return Response( {'message': 'Account with this email already exists'}, status=status.HTTP_400_BAD_REQUEST,) else: return Response( {'message': 'Username already exists'}, status=status.HTTP_400_BAD_REQUEST) else: return Response( {'message': 'Password must be at least 8 characters in length'}, status=status.HTTP_400_BAD_REQUEST) else: return Response( {'message': 'Passwords do not … -
Can't see images in Django Rest Framework response
These are the serializers class EntityPhotosSerializer(serializers.ModelSerializer): image = serializers.SerializerMethodField('get_image') def get_image(self, entity): if not entity.image: return request = self.context.get('request') return request.build_absolute_uri(entity.entity.url) class Meta: model = EntityPhoto fields = ('user', 'entity', 'image',) class SpecialistSerializer(serializers.ModelSerializer): reviews_quantity = serializers.IntegerField(source="get_reviews_quantity") entity_photos = EntityPhotosSerializer(many=True, read_only=True) class Meta: model = Entity fields = '__all__' class SpecialistDetailAPIView(generics.RetrieveAPIView): queryset = Entity.objects.all() serializer_class = SpecialistSerializer lookup_field = 'pk' class EntityPhoto(models.Model): user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, related_name='entity_photo') entity = models.ForeignKey(Entity, on_delete=models.CASCADE, null=False) image = models.FileField(upload_to='entities/') created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) Entity model doesn't have any fields connected to EntityPhoto, but EntityPhoto has entity on foreign key. So i'd want to see all the photos connected to an Entity, when i see entity/id/detailview. I tried adding the field entity_photos but in the response i get everyhing but entity_photos. Like its hidden. Do you know how can i show the photos that have entity_id == self.kwargs['pk']? -
django: unable to save new user
I'm trying to build a view that shows a form for creating a new user. Next are the template I'm using and the code attempts at views.py and forms.py. user_form.html <form action="{% url 'app:register' %}" method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Register"> </form> First attempt: views.py class NewUser(generic.CreateView): model = User fields = ['username','email','password'] template_name = 'app/user_form.html' success_url = reverse_lazy('register') This one didn't return errors, but was unable to save the new user data. Second try involved creating a form for the occasion: forms.py class NewUserForm(forms.Form): username = forms.CharField(max_length=100) email = forms.EmailField() password = forms.PasswordInput() views.py class NewUser(generic.CreateView): model = User fields = ['username','email','password'] template_name = 'app/user_form.html' success_url = reverse_lazy('register') This one returned an error: TypeError at /newuser/ BaseForm.__init__() got an unexpected keyword argument 'instance' Third: forms.py class NewUserForm(forms.ModelForm): class Meta: model = User fields = ['username','email','password'] views.py class NewUserView(generic.CreateView): model = User form_class = NewUserForm template_name = 'app/user_form.html' success_url = reverse_lazy('cadastro') Can't save a new User instance either. I've also noticed that the model = User line in this last try can be removed. I'm using the User.objects.all() query in the terminal and the admin page to check for new users. What am I not doing? -
'BaseUserManager' object has no attribute 'create_superuser'
We have a django application with a custom user model class CustomUser(AbstractUser): ... the model is also registered in settings.AUTH_USER_MODEL. When attempting to create a new user using python manage.py createsuepruser I get the following error File "D:\APP\webapp\backend\webserver\manage.py", line 22, in <module> main() File "D:\APP\webapp\backend\webserver\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\USER\.conda\envs\webdev2\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\USER\.conda\envs\webdev2\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\USER\.conda\envs\webdev2\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\USER\.conda\envs\webdev2\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "C:\Users\USER\.conda\envs\webdev2\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\USER\.conda\envs\webdev2\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) AttributeError: 'BaseUserManager' object has no attribute 'create_superuser' -
Unable to start the server in Django after including polls.urls in mysite/urls.py
I was creating my first view using this in Django I have included all the codes mentioned. I included the below code in ~/testsite/polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] And I added the line in ~/testsite/testsite/urls.py from django.contrib import admin from django.urls import path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] When I start the server in linux using $ python3 manage.py runserver This is the error I'm getting Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.9/dist-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/dist-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.9/dist-packages/django/core/management/base.py", line 438, in check all_issues = checks.run_checks( File "/usr/local/lib/python3.9/dist-packages/django/core/checks/registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.9/dist-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.9/dist-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.9/dist-packages/django/urls/resolvers.py", line 448, in check for pattern in self.url_patterns: File "/usr/local/lib/python3.9/dist-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.9/dist-packages/django/urls/resolvers.py", line 634, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.9/dist-packages/django/utils/functional.py", line 48, in … -
'HttpResponseRedirect' object has no attribute 'authorize' Python Django youtube-api Web
I can't get permission. This error comes out. What to do? I called the get_user_info function by passing the user's primary key and its token in arguments. Then, in the get_user_info function, the get_service function is called to gain access to the user's YouTube account. The problem occurs when I try to redirect the user to a page with permission to get information about his account. TOKEN_FILE = json.dumps(GlobalSettings.objects.first().secret_token) APP_TOKEN_FILE = json.loads(TOKEN_FILE) SCOPES = ["https://www.googleapis.com/auth/youtube.readonly"] def get_creds_saved(current_user_pk, USER_TOKEN): creds = None if USER_TOKEN is not None: creds = Credentials.from_authorized_user_info(USER_TOKEN, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_config(APP_TOKEN_FILE, SCOPES) flow.redirect_uri = 'https://oxy-cash.ru/earnmoney/' authorization_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true') return redirect(authorization_url) # user = CustomUser.objects.get(pk=current_user_pk) # user.user_token = creds.to_json() # user.save() return creds def get_service(current_user_pk, USER_TOKEN): creds = get_creds_saved(current_user_pk=current_user_pk, USER_TOKEN=USER_TOKEN) service = build('youtube', 'v3', credentials=creds) return service def get_user_info(current_user_pk, USER_TOKEN): channel = get_service(current_user_pk=current_user_pk, USER_TOKEN=USER_TOKEN).channels().list(part="snippet,contentDetails,statistics", mine=True).execute() info = { 'username': channel['items'][0]['snippet']['title'], 'photo': channel['items'][0]['snippet']['thumbnails']['default']['url'] } return info def app_earnmoney(request): if request.user.is_authenticated: current_user = CustomUser.objects.get(pk=request.user.pk) is_next_day(current_user) info = get_user_info(current_user_pk=request.user.pk, USER_TOKEN=current_user.user_token) Error -
Validating email format in Django
I am trying to create a simple registration page in Django and to check all fields validation. I tried to check the email field format validation but I could not find any source to do that. Can you help me please? Here is the view.py: from django.shortcuts import render from django.http import HttpResponse, request from django.db import connection from django.contrib.auth.decorators import login_required import pyodbc def newUser(request): form = NewUserFrom(request.POST or None) if not form.is_valid(): context = {'frmNewUser':form} return render(request,'login/newuser.html', context) return render(request, "login/welcome.html") Here is the forms.py: from ctypes import alignment from email import message from urllib import request from django import forms class NewUserFrom(forms.Form): error_css_class = 'error' username = forms.CharField(max_length=50, widget=forms.TextInput, label="Username") password = forms.CharField(widget=forms.PasswordInput, label="Password") confirm_password = forms.CharField(label="Confirm password", widget=forms.PasswordInput) name = forms.CharField(max_length=50, widget=forms.TextInput, label="Name") email = forms.EmailField(max_length=50, widget=forms.EmailInput, label="Email") def clean_password(self): cleaned_data = super().clean() pwd = cleaned_data.get('password') cof_pwd = cleaned_data.get('confirm_password') # if pwd and cof_pwd: if pwd != cof_pwd: raise forms.ValidationError('Password is not match.') return cleaned_data def clean(self): cleaned_data = super(NewUserFrom,self).clean() email = cleaned_data.get('email') if email.strip() == "".strip(): # self.add_error('email','Email is reqiered.') raise forms.ValidationError('Email is reqiered.') else: fistPart, secPart = str(email).split('@') raise forms.ValidationError('Email error.') Here is the NewUser.html: {% block content %} <form method="POST"> {% csrf_token %} … -
Exclude field from Django validation in admin form
I am working on project with a lot of legacy code base. I have a custom model field for price that goes like this class PriceField(PositiveIntegerField): def get_prep_value(self, value: float) -> Optional[int]: return int(value * 100) if value else self.default def from_db_value(self, value: int, expression, connection) -> Optional[float]: return value / 100 if value else value class Expertise(models.Model): price = PriceField(blank=True, default=0, help_text='Price per min.') ... Prices are stored in db multiplied by 100, e.g. 9.90 is stored as 990, and values are obtained from db in human readable way (990 as 9.90). Now I am facing a problem with default PositiveIntegerField Django admin form validation for that field. Because this value represented as float every time I click "Save" I get a PositiveIntegerField's ValidationError. Is there any way to exclude this field from admin form validation or to send this field value multiplied by 100? -
Unable to upload files/images to cloud storage (GCP) with Django
I am trying to upload files & images to the GCP bucket which I created a while ago. I am using Django rest-framework as the backend. I came across this library called [django storages][1]. I did everything stated in the library documentation. Create a service account, provided permission as storage admin and generated the json key. In my projects settings.py file I have declared these attributes - DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_BUCKET_NAME = os.environ.get("GS_BUCKET_NAME") GS_CREDENTIALS = service_account.Credentials.from_service_account_file("ibdax.json") GS_PROJECT_ID="project-id" Additionally, my models look exactly the same as said in the documentation. But I still get this error - { "error": "HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Max retries exceeded with url: /token (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0xffffa84881d0>: Failed to establish a new connection: [Errno 111] Connection refused'))" } These are the logs - Internal Server Error: /api/properties/create-property/ ibdax | Traceback (most recent call last): ibdax | File "/usr/local/lib/python3.7/site-packages/asgiref/sync.py", line 482, in thread_handler ibdax | raise exc_info[1] ibdax | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 38, in inner ibdax | response = await get_response(request) ibdax | File "/usr/local/lib/python3.7/site-packages/django/utils/deprecation.py", line 138, in __acall__ ibdax | )(request, response) ibdax | File "/usr/local/lib/python3.7/site-packages/asgiref/sync.py", line 444, in __call__ ibdax | ret = await asyncio.wait_for(future, timeout=None) ibdax | File "/usr/local/lib/python3.7/asyncio/tasks.py", line 414, in wait_for … -
Structuring multi-apps Django project to minimize import dependancies
I am trying to reorganize my project in order to minimize dependancies and get rid of potential circular imports, especially when doing the first migrations on an empty database to create the apps from scratch. To minimize those dependancies, I currently have 4 apps: puzzles (contains all info about puzzles) users (all info about users) games (everything that relates to a user performing a puzzle) puzzle_explorer (generates new puzzles) I'm however interested (for instance) by the number of users that completed a specific puzzle, so I first defined a property nb_users_who_completed in the puzzles.Puzzle model ... which leads to two-directional dependancies and potential circular imports Because in reality, there are of course a lot more models, and lot more cross-app properties, quick and dirty won't be sustainable. I've first thought about "extending" the different models (plus managers) in puzzles through Mixins: #in games: class Puzzle_Games_Mixin(object): @property: def nb_users_who_completed(self): return pass def custom_method1(self): pass # in puzzles: from games.mixins import Puzzle_Games_Mixin class Puzzle(Puzzle_Games_Mixin, models.Model) That makes the modularity more clear, but does not really help in term of solving circular imports The second strategy I thought of, is to extend in games the Puzzle model with the extra cross-application functionalities (as … -
Django: Fill model fields attributes from current fields
In my current item model, I want to fill the model fields by using calculations within the init. class Items(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) item_name = models.CharField(max_length=200, null=False, blank=False, default='Enter name') item_category = models.ForeignKey(Categories, null=True, blank=True, on_delete=models.SET_NULL) item_created_at = models.DateTimeField(auto_now_add=True, null=True, blank=False) item_start_date = models.DateField(null=True, blank=False) item_end_date = models.DateField(null=True, blank=False) item_purchase_price = models.FloatField(null=True, blank=False) item_rest_value = models.FloatField(null=True, blank=False) item_saving_goal = models.FloatField(default=0, null=True, blank=False) item_date_delta = models.FloatField(default=0, null=True, blank=False) item_days_passed = models.FloatField(default=0, null=True, blank=False) item_currently_saved = models.FloatField(default=0, null=True, blank=False) item_percentage_saved = models.FloatField(default=0.01, null=True, blank=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.item_saving_goal = self.item_purchase_price - self.item_rest_value self.item_date_delta = self.item_end_date - self.item_start_date self.item_days_passed = (date.today() - self.item_start_date).float() ## Make date calc self.item_currently_saved = self.item_saving_goal * (self.item_rest_value / self.item_date_delta ) self.item_percentage_saved = self.item_currently_saved / self.item_saving_goal * 100 However, I currently get the following error: TypeError at /items/ unsupported operand type(s) for -: 'NoneType' and 'NoneType' C:\Users...\base\models.py, line 43, in init self.item_saving_goal = self.item_purchase_price - self.item_rest_value -
prefetch by related_name in children foreign key django
i'm trying to prefetch related from parent model to chidren throught the related name, However the queryset in the template still hits the DB in PostgreSQL, my modelB modelC and ModelD all point towards modelA and when I overwrite the generic class based view queryset function it still doesnt affect the size of the query?? any clues ? *MODEL class ModelA(models.Model): title = models.Charfield(max_lenght=200, null=True, Blank=True) class ModelB(models.Model): model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE, related_name="model_a_related") *VIEW class ModelAView(DetailView): model = ModelA def get_queryset(self): return super().get_queryset().prefetch_related('model_a_related') -
drf-yasg - description for filter parameters
I'm curious if there is a way to tell the yasg to add description to django-filter parameters. I want to tell developers that the parent field is a Country model pk. Model class County(AddressModel): parent = models.ForeignKey('Country', verbose_name='Krajina', related_name='counties', on_delete=models.PROTECT, help_text='Krajina') class Meta: verbose_name = 'Kraj' verbose_name_plural = 'Kraje' Filter class CountyFilter(FilterSet): class Meta: model = County fields = { 'name': ['icontains'], 'parent': ['exact'] } Serializer class CountySerializer(serializers.ModelSerializer): class Meta: model = County fields = ['id', 'name'] View class AddressCountyAutocompleteView(ListAPIView): serializer_class = CountySerializer filter_backends = [DjangoFilterBackend] filterset_class = CountyFilter queryset = County.objects.all() pagination_class = AddressAutocompletePagination def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) This is the auto-generated swagger: Is it possible to do that without writing a custom scheme? -
Get all categories and object assigned to sub-categrory django MPTT
#simplified version of model class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Product(models.Model): category = TreeForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=150) def __str__(self): return self.name What I want to do is for every category without a parent, I want to return its sub categories and product within the category Eg: Category.objects.get(id=1) will return in template category: product # can directly attach to parent category subcategory product subcategory How do I accomplish this? I have tried category.get_descendants(include_self=True) returns <TreeQuerySet [<Category: sub section>]> -
django inline formset same value is repeated
I want to set employee target for every product, its showing all product but only one product saving everytime i want all product with different target In my Views.py class targetcreate(CreateView): model = target form_class = targetform1 success_url = '/' def get_context_data(self,** kwargs): context = super(targetcreate, self).get_context_data(**kwargs) context['formset'] = targetFormset(queryset=target.objects.none(), instance=product.objects.get(id=1),initial=[{'name': name} for name in self.get_initial()['name']]) return context def get_initial(self): initial = super(targetcreate , self).get_initial() initial['name'] = product.objects.all() # initial['name'] = add_users.objects.all() return initial def post(self, request, *args, **kwargs): formset = targetFormset(request.POST,queryset=target.objects.none(), instance=product.objects.get(id=1), initial=[{'name': name} for name in self.get_initial()['name']]) if formset.is_valid(): return self.form_valid(formset,request) else: messages.warning(request,'error') return render(request,'add_target_emp1.html',{'formset':formset}) def form_valid(self,formset,request): instances = formset.save(commit=False) for instance in instances: instance.date = request.POST.get('date') instance.name = emp.objects.get(id=3).user.username instance.save() return redirect('../../accounts/add_target_emp1') in my models.py this is my employee model i have product in another app class emp(models.Model): user=models.OneToOneField(User,null=True,on_delete=models.CASCADE) firstname=models.CharField(default='',max_length=100,null=False) lastname=models.CharField(default='',max_length=100,null=False) gender=( ('M','Male'), ('F','Female'), ('O','Others'), ) gender=models.CharField(choices=gender, default='',max_length=10) dob=models.DateField(default=datetime.now) created_by=models.CharField(default='',max_length=100) phonenumber=models.TextField(default='',null=False,unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(default=timezone.now) branch=models.CharField(default='',max_length=100) position=models.CharField(default='',max_length=100) class target(models.Model): conversion_target=models.BigIntegerField(null=True) total_target=models.BigIntegerField(null=True) name=models.CharField(default='',max_length=100) branch=models.CharField(default='',max_length=100) created_at = models.DateTimeField(auto_now_add=True) created_by=models.CharField(default='',max_length=100) month=models.CharField(default='',max_length=100) vehicle=models.ForeignKey(product,on_delete=models.CASCADE,null=True) class product(models.Model): product_category=models.CharField(null=True,max_length=5000) product_category_id=models.CharField(null=True,max_length=5000) Value=models.DecimalField(default=0.00,max_digits=10,decimal_places=2) products=models.CharField(null=True,max_length=5000) forms.py class targetform1(ModelForm): class Meta: model = target fields ='__all__' widgets = {'name' : HiddenInput} exclude=['created_at','created_by','completed_total_target','completed_conversion_target','completed_total_percentage','completed_conversion_percentage','branch'] def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) for field in self.fields: new_data={ 'class':'form-control', 'rows':1, 'required':'True', } self.fields[str(field)].widget.attrs.update( new_data … -
Represent number as currenct from paragraph
On my web page I have an paragraph which looks like this: <p class="article-content mb-1" id="cost"><strong>Cost [Euro]: </strong>1000000</p> Number is always something else (which I read from db and represent using Django forms) and I would like to represent it as currency (in this case 1.000.000). I tried to get the value with: <script type="text/javascript"> function on_load(){ var a = document.getElementById('cost').value; console.log(a) } on_load(); </script> but Console output is: 'undefined'. When I get value, I'll use something like (12345.67).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); // 12,345.67 To convert to currency. -
Chart.js Django Everthing is Working fine but in index of graph there is 0.028 instead of date from the list
<canvas id="myChart" width="400" height="400"></canvas> <script> var final={{final|safe}}; var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for i in final %}{{i.Date}},{% endfor %}], datasets: [{ label: 'Actual Price', data: [{% for i in final %}{{i.Open}},{% endfor %}] }, { label: 'Prediction Price', data:[{% for i in final %}{{i.prediction}},{% endfor %}] }] }, options: { scales: { xAxes: [{ display: true }], yAxes:[{ ticks:{ beginAtZero: true } }] } } }); </script> </div> Graph Console Chart.js Django Everthing is Working fine but in index of graph there is 0.028 instead of date from the list.Chart.I uses a For loop to for getting Value from list name final then i run the for loop on labels to get the value of date but in graph there is no any date -
fail compiling GDAL 3.0.4 on AMI 2
I have the following output after trying to do a make install echo 'CONFIG_VERSION='`cat ./VERSION`'' >> gdal.pc echo 'CONFIG_INST_PREFIX=/usr/local' >> gdal.pc echo 'CONFIG_INST_LIBS=-L/usr/local/lib -lgdal' >> gdal.pc echo 'CONFIG_INST_CFLAGS=-I/usr/local/include' >> gdal.pc echo 'CONFIG_INST_DATA=/usr/local/share/gdal' >> gdal.pc cat gdal.pc.in >> gdal.pc /usr/local/gdal/gdal-3.0.4/install-sh -d /usr/local/lib for f in libgdal.la ; do /bin/sh /usr/local/gdal/gdal-3.0.4/libtool --mode=install - silent /usr/local/gdal/gdal-3.0.4/install-sh -c $f /usr/local/lib ; done install: .libs/libgdal.lai does not exist make: *** [install-lib] Error 1 -
Django server not initializing with Docker?
I'm new to Docker, and I'm not being able to make it work. I'm on Windows. I cloned the repository https://github.com/18F/docker-compose-django-react, went to VSCode and built the containers with the "Remote - Containers" extension. When I try to access http://localhost:8000/, I get the message "localhost didn’t send any data.", although the React http://localhost:3000/ loads correctly. If I open the terminal from inside the Container, go to the correct folder and run python manage.py runserver, I can access it normally. So it seems that the server isn't being initialized on the Dockerfile/docker-compose. I'm also having this trouble on a setup I'm trying to make from some blog posts. How can I fix/debug this? -
Django implementation of if-else statement
I want to implement a django payment system using a payment platform named mpesa. I also want to print "hello world" on the console every time the page loads or when the request.POST.get('action') == 'post' is not triggered when the function is accessed. I have my code below. def pay_online(request): response_data = {} current_user = request.user queryset = Individual.objects.filter(user = request.user.id) if queryset.exists(): queryset = Individual.objects.get(user = request.user.id) else: queryset = Business.objects.get(user = request.user.id) if request.POST.get('action') == 'post': print("hello world 1") MpesaNo = request.POST.get('mpesaNumber') response_data['message'] = "Check your phone for ussd prompt to complete the payment." access_token = MpesaAccessToken.validated_mpesa_access_token api_url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest" headers = {"Authorization": "Bearer %s" % access_token} request = { "BusinessShortCode": LipanaPpassword.Business_short_code, "Password": LipanaPpassword.decode_password, "Timestamp": LipanaPpassword.lipa_time, "TransactionType": "CustomerBuyGoodsOnline", "Amount": queryset.ccTotal, "PartyA": Number, "PartyB": LipanaPpassword.Business_short_code, "PhoneNumber": Number, "CallBackURL": "https://sandbox.com", "AccountReference": "Trial", "TransactionDesc": "Trial payments" } response = requests.post(api_url, json=request, headers=headers) return JsonResponse(response_data) else: print("hello world") context = {'queryset':queryset} template = 'payments_page.html' return render(request, template, context) My main question is why this is not displaying "hello world" on the console when request.POST.get('action') == 'post' is not triggered.