Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
python manage.py startapp item doesn't work for me
I saw this command work in my django video courses but unfortunately it doesn't work for me when I enter python manage.py startapp item it returns an error which says : File "D:\Django\puddle\manage.py", line 22, in <module> main() File "D:\Django\puddle\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Django\env\lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "D:\Django\env\lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "D:\Django\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\Django\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "D:\Django\env\lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\Msk\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'item' I just tried to install this app to learn the rest of the Django course but it says the item module not found! -
How to avoid client caches (Chrome) on django react app?
I have a django-react app that is serving out of Heroku. I use webpack to build static files, which I serve out of a Django app called frontend. Django static files serving adds a hash to the webpack generated files for cache breaking on new releases. To illustrate, here is the index.html that is served for my site: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="/static/favicon.e62ca627caf.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <link rel="stylesheet" type="text/css" href="/static/frontend/css/index.e861872e9ba7b.css"/> <link rel="manifest" href="/static/manifest.a22d2aecab21fe.json" /> </head> <body> <div id="root"></div> <script src="/static/frontend/js/index.a39c981a0accf.js"></script> </body> </html> Cache-Control for index.html is set to max-age=0. I thought this setup would be good enough for breaking client caches when I release a new frontend version of my site (since index.*.js would have a new hash). However, I observed that some of my clients had stale versions up to two weeks ago even with this setup (using Chrome on Windows). How is this possible? Am I missing something to break client caches for new frontend releases? -
Django and tensorflow app deployed with heroku
I am sorta new to django and heroku and but I made a django app which intakes user values, processes them through a tensorflow model which was trained and loaded by doing: enter image description here Locally, my app works just fine but now I am trying to deploy it using heroku and I am finding lots of trouble. My main issue is when I run 'git push heroku main' this is what I get: enter image description here I have tried changing my python versions even using different tensorflow versions as well. I am currently in python-3.11.6 but I have tried running this with python-3.10.13 and python-3.9.18. If anyone can help that would be appreciated. Thank you for your time. -
Django with html chartjs
"I use Django to create a web app with HTML, and I want to change the format of numbers in the graph from 123456.123456 to 123,456.12. I've tried using floatformat:'2g' or .toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","), but the values in each point are separated by commas, like [1123,2212]. The expected result should be like 1,123 and 2,212 as usual, but in the graph, I get: Point 1: 1 Point 2: 123 Point 3: 2 Point 4: 212 Please help." my code : new Chart(chartLineCanvas, { type: 'line', data: { labels: labels, datasets: [ { label: 'Total Sales (Baht)', borderColor: 'rgba(0, 0, 255, 1)', backgroundColor: 'rgba(0, 0, 255, 0.2)', data: data }, { label: 'Average Sales Present (Baht)', borderColor: 'rgba(255, 165, 0, 1)', backgroundColor: 'rgba(255, 0, 0, 0)', data: Array(data.length).fill(data.reduce((a, b) => a + b, 0) / data.length), }, { label: 'Average Sales Before(Baht)', borderColor: 'rgba(255, 0, 0, 1)', backgroundColor: 'rgba(255, 0, 0, 0)', data: Array(averagedata.length).fill(averagedata.reduce((a, b) => a + b, 0) / averagedata.length), }, ], }, options: { mode: 'index', bodyFontSize: 20, locale: 'en-US', tooltips: { callbacks: { label: function (tooltipItem, data) { var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || ''; var value = tooltipItem.yLabel; return datasetLabel + ': ' + value.toLocaleString('en-US', { style: 'decimal', … -
Problems with django testing?
I am developing a django app and currently testing it as well, this is my view: from django.http import JsonResponse, HttpResponseBadRequest from store.models import Product from .basket import Basket # Create your views here. def basket_summary(request): basket = Basket(request) return render(request, "store/basket/summary.html", {"basket": basket}) def basket_add(request): basket = Basket(request) if request.POST.get("action") == "post": product_id = int(request.POST.get("productid")) product_qty = int(request.POST.get("productqty")) product = get_object_or_404(Product, id=product_id) basket.add(product=product, product_qty=product_qty) basket_qty = basket.__len__() response = JsonResponse({"qty": basket_qty}) return response def basket_delete(request): basket = Basket(request) if request.POST.get("action") == "post": product_id = int(request.POST.get("productid")) basket.delete(product_id=product_id) basket_qty = basket.__len__() basket_total = basket.get_total_price() response = JsonResponse({"qty": basket_qty, "subtotal": basket_total}) return response def basket_update(request): basket = Basket(request) if request.POST.get("action") == "post": product_id = int(request.POST.get("productid")) product_qty = int(request.POST.get("productqty")) basket.update(product_id=product_id, product_qty=product_qty) basket_qty = basket.__len__() basket_total = basket.get_total_price() response = JsonResponse({"qty": basket_qty, "subtotal": basket_total}) return response My urls.py file is also below: from .views import basket_summary, basket_add, basket_delete, basket_update app_name = "store_basket" urlpatterns = [ path("", basket_summary, name="basket_summary"), path("add/", basket_add, name="basket_add"), path("delete/", basket_delete, name="basket_delete"), path("update/", basket_update, name="basket_update"), ] Finally my testing file: from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from store.models import Category, Product from json import loads class TestBasketView(TestCase): def setUp(self): category = Category.objects.create(name="django", slug="django") user = User.objects.create(username="admin") … -
format datetimeinput in django
I have a booking site and I want the booking to be permanent only by hours (I don't want minutes) an example of John booked from 8 to 10 o'clock And I don't want 8:10 to 10: 30 pm Can I remove the minutes from DateTimeInput format that the user cannot choose them and selects only the hour look at the picture here enter image description here Or any other way to do this -
Docker Compose - could not translate host name "database" to address: Name or service not known
When i run docker-compose up it gives me this error. Im using Django and React to build the application, as listening with gunicorn for server. I know i dont need to create a network because compose do this byself, but i tryed everything i found and nothing solved my problem, any sugestions? django.db.utils.OperationalError: could not translate host name "database" to address: Name or service not known failed to solve: process "/bin/sh -c python manage.py migrate" did not complete successfully: exit code: 1 Dockerfile FROM python:3.9.13 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY . /app WORKDIR /app RUN pip3 install -r requirements.txt RUN python manage.py makemigrations RUN python manage.py migrate CMD gunicorn -b 0.0.0.0:8000 --worker-class=gevent --worker-connections=1000 --workers=5 backend.wsgi docker-compose.yaml version: "3" services: database: container_name: database networks: - djangonetwork image: postgres:12.7-alpine expose: - "5432" volumes: - ./backup_data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=dockerteste - POSTGRES_USER=postgres - POSTGRES_PASSWORD=pw1234 backend: build: ./finapp volumes: - ./finapp:/app depends_on: - database networks: - djangonetwork frontend: build: ./frontend volumes: - ./frontend:/app depends_on: - backend ports: - 80:80 nginx_backend_server: build: ./nginx ports: - 8000:8000 depends_on: - backend networks: djangonetwork: driver: bridge -
How to pass a list of dates from Django ORM to a javascript date list to use as labels in chart.js
I'm trying to plot some charts comparing the close price of pairs of stocks in a timeline. My Django view.py function looks like this: # Access stock pairs for the user settings stock_pairs = StockPair.objects.filter(setting=setting) # Create a context dictionary including, for each stock_pair in stock_pairs, the close prices of the stocks in the pair and pass the dictionary to the template context = {} stocks_and_pair_data_list = [] for stock_pair in stock_pairs: stocks_and_pair_data = {} stocks_and_pair_data['stock1_name'] = stock_pair.stock1.name stocks_and_pair_data['stock2_name'] = stock_pair.stock2.name stocks_and_pair_data['dates'] = [dt for dt in stock_pair.stock_pair_data_set.values_list('date', flat=True)] stocks_and_pair_data['stock1_close_prices'] = [float(close) for close in stock_pair.stock1.stock_data_set.values_list('close', flat=True)] stocks_and_pair_data['stock2_close_prices'] = [float(close) for close in stock_pair.stock2.stock_data_set.values_list('close', flat=True)] stocks_and_pair_data_list.append(stocks_and_pair_data) context['stocks_and_pair_data_list'] = stocks_and_pair_data_list return render(request, 'my_page.html', context) and my_page.html has this script section: <!-- For each stocks_and_pair_data in stocks_and_pair_data_list create, using chart.js, a chart of the close prices of stock1 and stock2 --> {% for stocks_and_pair_data in stocks_and_pair_data_list %} <script> const ctxClose = document.getElementById('ChartOfClosePrices{{ forloop.counter }}'); new Chart(ctxClose, { type: 'line', data: { labels: '{{stocks_and_pair_data.dates}}', datasets: [{ label: '{{ stocks_and_pair_data.stock1_name }}', data: '{{stocks_and_pair_data.stock1_close_prices}}' },{ label: '{{ stocks_and_pair_data.stock2_name }}', data: '{{stocks_and_pair_data.stock2_close_prices}}' }] } }); </script> {% endfor %} I'm having 2 problems. The first problem is that I get the following error on the browser …