Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
whenever I try to import my Model into my APP's view I get this annoying error
so this is my app's view that is called "Movies" from django.shortcuts import render from .models import Movie def content_view(request,*args,**kwargs): obj= Movie.objects.get(id=1), context={'Title':Title, 'Description':obj.Description, 'watch now': obj.Watch_Now, 'imdb': obj.IMDB_Rate, 'RT' : obj.RT_Rate, 'my rate': obj.My_Website_rate } return render(request,'content.html',context) and this is the error I get: Model class src.Movies.models.Movie doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS and yes my app is in installed app in settings. if I comment the second line that import my model, the server runs okay I've been trying to fix it for past 6 hours but I can't reach any solution. please HELP -
Getting database "test-instance" does not exist while trying to containerize python app
I am trying to containerize a python app and it has a postgres db which is in GCP cloud. But when I build the app its throwing an error telling the database does not exist i am unable to understand what is happening i can connect to the database by using Dbeaver tool but when I run the docker file I can see the logs that say File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: database "test-instance" does not exist Docker file which i used # Pull base image FROM python:3.9 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY requirements.txt /code/ RUN pip install -r requirements.txt # Copy project COPY . /code/ settings.py file how i reach out to the gcp db DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-instance', 'USER': 'postgres', 'PASSWORD': 'abcder', 'HOST': '35.224.136.9', 'PORT': '5432', } } -
Cors or Axios Error on Django Server and React frontend project
When trying to connect my react component to the django server after installing corsheaders and adding it to installed apps in settings.py. I am still getting the following error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/teacher/. (Reason: CORS request did not succeed). Status code: (null). I have already installed corsheaders and added it to my settings.py together with its middleware, and put allowed all cors origins in same file. I have also installed axios in react and put the import in my react component -
Error, unable to determine correct filename for 64bit macos for using instapy
Justibbs007@Ibrahims-MacBook-Pro ~ % /usr/local/bin/python3 /Users/Justibbs007/programs/instapy-quickstart-master/quickstart_templates/basic_follow-unfollow_activit y.py InstaPy Version: 0.6.16 .. .. .. .. .. .. .. .. .. .. Workspace in use: "/Users/Justibbs007/InstaPy" Error, unable to determine correct filename for 64bit macos Traceback (most recent call last): File "/Users/Justibbs007/programs/instapy-quickstart-master/quickstart_templates/basic_follow-unfollow_activity.py", line 31, in session = InstaPy(username=insta_username, File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/instapy/instapy.py", line 330, in init self.browser, err_msg = set_selenium_local_session( File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/instapy/browser.py", line 122, in set_selenium_local_session driver_path = geckodriver_path or get_geckodriver() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/instapy/browser.py", line 38, in get_geckodriver sym_path = gdd.download_and_install()[1] File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/webdriverdownloader/webdriverdownloader.py", line 174, in download_and_install filename_with_path = self.download(version, File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/webdriverdownloader/webdriverdownloader.py", line 129, in download download_url = self.get_download_url(version, os_name=os_name, bitness=bitness) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/webdriverdownloader/webdriverdownloader.py", line 324, in get_download_url raise RuntimeError(info_message) RuntimeError: Error, unable to determine correct filename for 64bit macos please can someone help me out please -
Prevent celery from running my Django app threads
I have a Django app and I am using celery (with redis) for running processing tasks in the background. In addition, I have a python thread which runs some periodic checks as part of my Django app. Surprisingly, when I am starting celery I see my thread is also running as part of celery. I would like to prevent this behavior and have only one instance of my thread and have it as part of my Django app. How can I prevent it from running in celery? I tested it on a newly created app and see the exact same behavior: settings.py: ... CELERY_BROKER_URL = 'redis://localhost:6379/1' __init__.py: from threading import Thread from time import sleep from .celery import app as celery_app __all__ = ('celery_app',) def mythread(): while True: print("thread is running") sleep(10) new_thread = Thread(target=mythread, daemon=True) new_thread.start() celery.py: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() -
DM Messages not lining up
Social Media Platform: I am trying to get the image to line up above the sent message as you would have it in most standard DMs: https://i.stack.imgur.com/vyO2b.png But for some reason, the text attached to the image proceeds to layer itself beside the image rather than below the image, as shown in the screenshot below. When I add float: right; to my CSS the image and the text layer horizontally in a strange manner: Not lining up Ideally, the image should be on the same side as the texts from the person who sent the image and should be just above the message that was attached to the image (as is commonplace). The HTML doc the DMs are stored on: thread.html: > {% extends 'landing/base.html' %} {% load crispy_forms_tags %} > > {% block content %} > > <div class="container"> > <div class="row"> > <div class="card col-md-12 mt-5 p-3 shadow-sm"> > {% if thread.receiver == request.user %} > <h5><a href="{% url 'profile' thread.user.profile.pk %}"><img class="rounded-circle post-img" height="50" width="50" > src="{{ thread.user.profile.picture.url }}" /></a> @{{ thread.user > }}</h5> > {% else %} > <h5>@{{ thread.receiver }}</h5> > {% endif %} > </div> > </div> > > {% if message_list.all.count == 0 … -
GUI library in Python to collapse adjustable shapes such as rectangles?
I'm new to Python, and am currently working on web development in Django. I need to have an interface on this website that allows a user to dynamically adjust a rectangular shape that displays this adjustment to them on the website in real time. Does anyone know a way to do this using other Python libraries, and how easily those libraries can be integrated into a Django project? Pretty much I need a way to display to the user a rectangle that they can drag and drop the lengths of on the screen as they desire. Very similar to the MS Word shape drawing tools where the user can pick the edge of and expand or collapse. I have explored different libraries in Python, and have found nothing concrete to do this. Any avenues for exploration would be appreciated. -
Make a booleanfield change based on the input of another field in another form and model
I'm trying to make the Status booeleanField in the class References change based on the choice input of the action charfield in the class Ecran after the form submission. For example if i select "sortir pour production" in the action field, the Status field automatically changes to False and if i choose the "retour en stock" it changes to true. Also i want to change the false/true of the status booleanfield to show up in the list_references template as simple Indicator icons, red circle for false and green circle for true. list_references page NOTE: the ETAT colum is the Status booleanField in class References. suivi_ref the form with the action charfield the form that has the Status booleanfield curerntly i can only change it from here models.py class References(models.Model): Ref = models.CharField(max_length=255, blank=False, null=True) Designation = models.CharField(max_length=100, blank=False, null=True) Indice = models.CharField(max_length=100, blank=False, null=True) Emplacment = models.ForeignKey(place, blank=False, null=True, on_delete=models.SET_NULL) Num = models.ForeignKey(Rayons, blank=True, null=True, on_delete=models.SET_NULL) Client = models.ForeignKey(Client, blank=False, null=True, on_delete=models.CASCADE) Statut = models.BooleanField(default=True) def __str__(self): return self.Ref Action_choice = ( ('Sortie pour production', 'Sortie pour production'), ('Retour en stock', 'Retour en stock'), ) BOOL_CHOICES = ((True, 'OK'), (False, 'NOT OK')) class Ecran(models.Model): Nom_de_technicien = models.CharField(max_length=255, blank=True, null=True) Nom_de_CQ … -
How does Django know the path to my database?
Just following the Django tutorials and decided I would do them with Postgresql instead of SQLlite. I added the following to my settings file and everything worked: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'django_tutorial', 'USER': 'django_admin', 'PASSWORD': 'password123', 'HOST': '127.0.0.1', 'PORT': '5432' } } django_tutorial=> \dt List of relations Schema | Name | Type | Owner --------+----------------------------+-------+-------------- public | accounts | table | django_admin public | auth_group | table | django_admin public | auth_group_permissions | table | django_admin public | auth_permission | table | django_admin public | auth_user | table | django_admin public | auth_user_groups | table | django_admin public | auth_user_user_permissions | table | django_admin public | django_admin_log | table | django_admin public | django_content_type | table | django_admin public | django_migrations | table | django_admin public | django_session | table | django_admin (11 rows) My question is this - How does Django know where postgresql is located? Originally I thought the name was supposed to be the C:\ path, but it only needed the DB name? Like for example the docs say this about sqllite: The name of the database to use. For SQLite, it’s the full path to the database file. When specifying the path, … -
How do I create a temporary link to an image in Django?
I'm writing a REST API. Users should be able to upload an image and view it. That part is easy, the images get saved to the media root, and serving them is handled separately by NGINX on /media/. The problem is that the user needs to be able to generate a temporary link to their image. It can't be a simple redirect, because what's the point of a temporary link if the end user gets redirected to a permanent link? Is there a way in Django to redirect the request on the backend, fetch the image, and return it to the user on the same URL? If not, what's the proper way to do it? I've looked through Google for some 30 minutes, and couldn't find anything. I'm sorry if it's obvious and my search queries were just wrong. -
implementing structural Json file into Django Rest Framework to create a Rest API
I'm wondering if I can create a model that gets all this Json tree, conserving this structure. I already have 3 separate models with the 3 types: MP & TP & VFD, but I want to group them into 1 model that respects this structure of JSON. what is the structure that I need to make in my models.py? { "devices": { "device": [{ "type": "MN", "time": "18/05/2022, 15:15:15", "vfd_name": "MP1", "SN": "EMSMP001", "plant_name": "plant1", "gatway_name": "gw1", "adress": 1, "baud_rate": 9600, "voltage": 230, "current": 10, "active_power": 2.3, "reactive_power": 0.01, "apparent_power": 2.3, "FP": 0.99, "frequency": 49.98 }, { "type": "TR", "time": "18/05/2022, 15:15:15", "TP_name": "TR1", "SN": "EMSMP002", "plant_name":"plant1", "gatway_name":"gw1", "adress": 1, "baud_rate":1, "UA":1, "UB":1, "UC":1, "UAB":1, "UBC":1, "UAC":1, "IA":1 }, { "type": "VFD", "time": "18/05/2022, 15:15:15", "vfd_name": "MP1" }, { "type": "MN", "time": "18/05/2022, 15:15:15", "vfd_name": "MP1", "SN": "EMSMP001", "plant_name": "plant1", "gatway_name": "gw1", "adress": 1, "baud_rate": 9600, "voltage": 230, "current": 10, "active_power": 2.3, "reactive_power": 0.01, "apparent_power": 2.3, "FP": 0.99, "frequency": 49.98 }, { "type": "TR", "time": "18/05/2022, 15:15:15", "TP_name": "TR1", "SN": "EMSMP002", "plant_name":"plant1", "gatway_name":"gw1", "adress": 1, "baud_rate":1, "UA":1, "UB":1, "UC":1, "UAB":1, "UBC":1, "UAC":1, "IA":1 }, { "type": "VFD", "time": "18/05/2022, 15:15:15", "vfd_name": "MP1" }, { "type": "MN", "time": "18/05/2022, 15:15:15", "vfd_name": … -
How Can I generate and Print Multiple Unique Recharge PIN in Django
I am working on a Ticketing project where I want the admin to be to generate multiple unique numeric PINs that customers can purchase and can be validated on the app for event registration. Here is my Ticket Model class Ticket(models.Model): name =models.CharField(max_length=50) price = models.PositiveIntegerField() pin = models.CharField(max_length=6) def __str__(self): return self.name I want a situation where admin would be able to generate multiple PINs for a particular ticket with a click but don't know how to go about it so someone should please help with the best way of doing it. -
Can't import from psycopg2 on Mac M1 Monterey 12.3.1
After installing psycopg2-binary==2.9.1 via pip install -r requirements.txt, when I run python manage.py runserver command locally in a django project I get the following output and error: main() File "/Users/gabrielnaughton/development/tamato/manage.py", line 25, in main execute_from_command_line(sys.argv) File "/Users/gabrielnaughton/development/tamato/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/gabrielnaughton/development/tamato/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/gabrielnaughton/development/tamato/venv/lib/python3.9/site-packages/django/core/management/base.py", line 343, in run_from_argv connections.close_all() File "/Users/gabrielnaughton/development/tamato/venv/lib/python3.9/site-packages/django/db/utils.py", line 232, in close_all for alias in self: File "/Users/gabrielnaughton/development/tamato/venv/lib/python3.9/site-packages/django/db/utils.py", line 226, in __iter__ return iter(self.databases) File "/Users/gabrielnaughton/development/tamato/venv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/gabrielnaughton/development/tamato/venv/lib/python3.9/site-packages/django/db/utils.py", line 153, in databases self._databases = settings.DATABASES File "/Users/gabrielnaughton/development/tamato/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/Users/gabrielnaughton/development/tamato/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/Users/gabrielnaughton/development/tamato/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/opt/homebrew/Cellar/python@3.9/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File … -
How to run infinite loop in Django and Display Message on template after each Loop without breaking the loop
I need a run a function infinitely until we manually stop it. But after executing each loop we have to display the current loop result in the template. After displaying the result it continues to the next loop. How to execute this process flow. Please advise. -
Convert the binary api Response into a pdf file in python
I have to call a api which gives me the response in binary, now I have to convert this to a readable pdf and send as attachment in mail. While doing so I am getting the pdf but it's getting corrupted. api_data = response.text attachments = [{"content": data, "type": "application/pdf", "filename": "REPORT.pdf"}] Api response in postman looks like this %PDF-1.7 2 0 obj [/PDF /Text /ImageB /ImageC /ImageI] endobj 11 0 obj <</Length 12 0 R /Filter /FlateDecode >> stream X �}���6��� �� `1��‑V�WJ �q�$��|�;� .��K��Ӌ~�Nw;3Y��_R"����‑�7�8ye~��*V�(����_�z,���˾��J�g= ���p,~,������D Any help will be appreciated very much. -
How can I style a django form with css?
I tried looking for the answer earlier but couldn't seem to figure out a few things. I'm creating my form in a form.py file so its a python file. Here is my forms.py file : class UploadForm(ModelForm): name = forms.TextInput(attrs={'class': 'myfieldclass'}) details = forms.TextInput() littype = forms.TextInput() image = forms.ImageField() class Meta: model = info fields = ["name", "details", "littype", "image"] Here is my views.py function for it if it helps find the solution : def uploadform(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) print(request.FILES) if form.is_valid(): form.save() redirect(home) return render(request, 'uploadform.html', {'form': UploadForm}) To style it I thought I could do something like this which I found in another question : class MyForm(forms.Form): myfield = forms.CharField(widget=forms.TextInput(attrs={'class': 'myfieldclass'})) Except I have no idea how to link a css page to that python file. This is what I tried writing but i think it doesnt work because its meant for html but its in a python file : <link type="text/css" rel="stylesheet" href="templates/form.css"> And so I'm just not sure how to style my form. Thanks for any answers! -
Django-Summernote not displaying as intended when in a modal/hidden div
I'm having alot of issues when trying to place django-summernote in a modal or a div (with display: none;) that is toggled with jquery. The bottom is an example of me trying to fit it in a modal. My example is below html: {% extends 'XYZ/index.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <button href="#certValModal" data-toggle="modal" type="submit" class="btn btn-success btn-circle btn-sm glow-button"> <i class="fas fa-check"></i> </button> <!--CERT VAL MODAL--> <div id="certValModal" class="modal" data-easein="bounceUpIn" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Send for CERT validation?</h4> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button> </div> <div class="modal-body"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form | safe }} </form> </div> <div class="modal-footer"> <button class="btn btn-success" data-dismiss="modal" aria-hidden="true">Send</button> </div> </div> </div> </div> {% endblock content %} Here is views: class TestView(LoginRequiredMixin, TemplateView): template_name = 'XYZ/TEST.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = forms.ValidationNew() return context forms: class ValidationNew(forms.ModelForm): content = SummernoteTextFormField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_action = 'add_validation' self.helper.add_input(Submit('submit', 'Submit')) class Meta: model = XYZValidation fields = ['content'] Please note: I have not set any custom settings in settings.py for django-summernote This is what summernote looks like … -
How do you post data in django with attribute depth=1 in the serializer?
I have a django model called “Enrolment” that depends on two other models through foreign key. “Course” model and “Enrolment” model. The “Course” model is like so: class Course(models.Model): name = models.CharField(max_length=100, blank=True) description = models.TextField(blank=True) prerequisite = models.TextField(blank=True) fee = models.FloatField(default=0.0) def __str__(self): return self.name And the Enrolment model is like so: class CourseEnrolment(models.Model): course_name = models.ForeignKey( Course, on_delete=DO_NOTHING) schedule = models.CharField(max_length=50, blank=True) student = models.ForeignKey( UserAccount, on_delete=DO_NOTHING) enrolment_date = models.DateTimeField(default=datetime.now()) def __str__(self): return self.course_name.name For me to gain access to the information about the enrolled course, I have to do like so in the CourseEnrolmentSerializer: class CourseEnrolmentSerializer(serializers.ModelSerializer): class Meta: model = CourseEnrolment depth = 1 fields = '__all__' With “depth = 1” being the secret to accessing information about the course. Now when I fetch enrolment, I get a response like below, which is exactly what I want like so. { "id": 5 "schedule": "June 23, 2022", "course_name": { "id": 4, "name": "fundamentals-of-programming", "description": "some description .", "prerequisite": "some prerequisite", "fee": 1000, }, "student": { "id": 1, "email": "martinsakinbo@yahoo.com", "first_name": "John", "last_name": "Doe", "phone": "1111111", } }, Now, the problem I have is that with “depth=1” in the serializer, I’m not able to create an enrolment when I … -
bootstarp grid system of django
MY problem I am implementing line breaks for more than 3 posts. and I set the grid with col-4 but Instead of being split middle the screen, they are gathered on the left. I want. 3 posts are located in the center so that a line break occurs every 3 how can i fix it? MY UNISEX.html {% extends "polls/base.html" %} {% block content %} {% load static %} <div class="container py-5"> <div> <p class="text-center fs-4 fw-bold">UNISEX</p> </div> </div> <!-- 사진크기 300px 400px --> <div class="container"> <div class="row"> {% for p in photo %} <div class="card col-4" style="width: 16rem; border: none"> <img src="{{ p.main_photo.url }}" class="card-img-top" alt="..."> <div class="card-body"> <p class=" card-text">{{ p.name }}</p> </div> </div> {% if forloop.counter|divisibleby:"3" %} </div> <div class="row"> {% endif %} {% endfor %} </div> </div> <div class="row"> </div> </div> <div class="container"> <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> <li class="page-item"> <a class="page-link" href="#" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> <li class="page-item"><a class="page-link" href="#">1</a></li> <li class="page-item"><a class="page-link" href="#">2</a></li> <li class="page-item"><a class="page-link" href="#">3</a></li> <li class="page-item"> <a class="page-link" href="#" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> </ul> </nav> </div> {% endblock %} Problem location <div class="container"> <div class="row"> {% for p in photo %} <div class="card col-4" style="width: 16rem; border: … -
Counting all items within django-treebeard Materialised Path nodes
I'm using django-treebeard to create a tree of Categories, each of which contains some Books: from django.db import models from treebeard.mp_tree import MP_Node class Book(models.Model): title = models.CharField(max_length=255, blank=False, null=False) categories = models.ManyToManyField("Category", related_name="books", blank=True) class Category(MP_Node): title = models.CharField(max_length=255, blank=False, null=False) book_count = models.IntegerField(default=0, blank=False, help_text="Number of Books in this Category") total_book_count = models.IntegerField(default=0, blank=False, help_text="Number of Books in this Category and its descendants") I want to display the number of Books in each Category, stored in Category.book_count, so I have a post_save signal like this: from django.dispatch import receiver @receiver(post_save, sender=Book) def book_post_save(sender, **kwargs): for category in kwargs["instance"].categories.all(): category.book_count = category.websites.count() category.save() (The reality is a bit more complicated, but this is the gist.) This works fine, and I can also do similar on an m2m_changed signal for if a Book's Categories have changed. BUT, I also want to calculate total_book_count - the total number of Books in a Category and in all of its descendant Categories. I can do this with a method like this on Category: def set_total_book_count(self): # All the Books in this Category's descendants: descendant_books = Book.objects.filter(categories__in=self.get_descendants()) # Combine with the Books in this Category but avoid counting duplicates: books = (descendant_books | self.books).distinct() … -
Connecting local data to Docker Django project
This is a question to understand what should be the best practice to follow in order to connect the dots on the argument. Currently I am developing a Dockerized Django website. In this website, one of the apps will be named 'dashboards', where I wish to publish data which is currently stored locally in .csv (updated every day through scheduled tasks). Now, I am trying to understand what should be the next steps to follow in order to connect these data to the Dockerized Django website. My first guess would be to schedule locally .sql scripts to 'append' the new data into the db that I can create locally. Then, connect the db to the Dockerized Django website through volumes belonging the postgreSQL service. Just a guess that I need to test. But, is there a way to skip everything locally and just do the work inside my Docker container? You can find the Github repository here. Many thanks! docker-compose.yml: version: '3.8' services: web: restart: always build: ./web expose: - "8000" links: - postgres:postgres - redis:redis volumes: - web-django:/usr/src/app - web-static:/usr/src/app/static env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn docker_django.wsgi:application -w 2 -b :8000 nginx: restart: always build: ./nginx/ ports: - … -
How to mock Django command which inserts data into django model
I am performing unittest on Django command which inserts the data received from API response into a database table. I am using unittest and mock to mock the the Command class and it's method, but I am not sure whether I am doing it correctly or not. Following is my code for Command and test: Command class Command(): def _insert_data(self, report_data, start_date): for data in report_data: self.cursor.execute(''' INSERT IGNORE INTO `report` ( `start_date`, `value_a`, `value_b`, `value_c`,`value_d`, ) VALUES (%s,%s,%s,%s,%s);''', ( str(start_date).split()[0], data['value_a'], data['value_b'], data['value_c'], data['value_d'] ) ) test_report_data.py from unittest import mock from base.test import BaseTestCase from client.models.intergration import Report from client.management.commands.update_report import Command as ReportCommand class CommandTestMixin(BaseTestCase): def setUp(self): super().setUp() self.mock_api_response = { "metrics": { "value_a": "123", "value_b": "123", "value_c": "1.48", "value_d": "1.0", } } self.mock_row = Report.objects.create( date = "2022-06-013" value_a = "123", value_b = "123" , value_c = "1.48", value_d = "1.0", ) def mock_response(self, json_data=None): mock_resp = mock.Mock() if json_data: mock_resp.json = mock.Mock( return_value = json_data ) return mock_resp class TestInsertReportData(CommandTestMixin): def setUp(self): super().setUp() def test_api_data_insert(self): command = ReportCommand() command._insert_data = mock.Mock() mock_resp = self.mock_response(json_data = self.mock_api_response) command._insert_data.return_value = self.mock_row command._insert_data(mock_resp, "2022-06-13") row = Report.objects.first() self.assertEqual(str(row.start_date), "2022-06-13") self.assertEqual(row.value_a, "123") self.assertEqual(row.value_b, "123") self.assertEqual(row.value_c, "1.48") self.assertEqual(row.value_d, "1.0") When … -
Django unit testing
I am testing my django code, but feel like i am missing something. Here is the view @login_required() def report_incident(request): template_name = "incident/report_incident.html" # request.post logic if request.method == "POST": form = IncidentForm(request.POST) if form.is_valid(): # use while loop to generate random unique id unique = False while not unique: id = generate_random_id(15) if Incident.objects.filter(incident_id=id).first() is None: unique = True # Assign unique id to form instance form.instance.incident_id = id # get incident type incident_type = form.instance.incident_type # If incident type is safeguading issue if str(incident_type.type).lower() == "safeguarding concerns": # if form instance of child is none, it means they used the text input # to write a new child name if not form.instance.child: # get the child name from the post request child_name = request.POST.get('childText') child_name = str(child_name) # create child object with new name unique = False while not unique: id = generate_random_id(15) if Child.objects.filter(child_id=id).first() is None: unique = True child = Child.objects.create(child_id = id, name=child_name) # add new child object to form instance of child form.instance.child = child #save form form.save() messages.success(request, "Incident reported succesfully") return redirect("report-incident") else: form = IncidentForm() context = {"form": form} return render(request, template_name, context) and here is the unit test class TestViews(TestCase): … -
how to print dictionary in django
I'm working on a translator program. I want the result to appear at the bottom of the original page when I presses the 'submit' button. There is no error, but there is no change when I press the 'submit' button. I want to show the contents of the dictionary by using table. This is my codes. 'trans_suc.html', 'views.py' and 'urls.py'. Please let me know how to modify it. trans_sub.html {% extends 'dialect/base.html' %} {% load static %} <!-- template 확장하기 body interface --> {% block content %} <!-- Masthead--> <div class = box> <div class = "container"> <form action="/trans/" method ="post"> {% csrf_token %} <input id = "trans" type ="text" name ="content" placeholder="0/500"> <input class = "btn" id="trans_btn" type ="submit" value ="번역"> </form> <!--<div><p>{{ content }}</p>--> {% for i in context %} <div> <table> <tr> <td>{{ i.siteName }}</td> <td>{{ i.contents }}</td> </tr> </div> {% endfor %} </div> </div> {% endblock content %} views.py class Postview(View): def get(self, request): massage = "hello" return render(request, 'dialect/main_page.html', {'msg': massage} ) @csrf_exempt def success(request): content = request.POST.get('content') context = { 'content': content } dict = pd.read_csv("C:\\Users\\user\\jeju-dialect-translation\\jeju\\dialect\\dict2.csv", sep=",", encoding='cp949') hannanum = Hannanum() okt = Okt() nouns = hannanum.nouns(content) stem = okt.morphs(content, stem = True) tempt=[] … -
Is there a way to filter out specific error messages using Django Logging? eg UncompressableFileError
Is there a way to filter out specific error messages using Django Logging? eg UncompressableFileError Would like to stop these errors being sent to Sentry.io