Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFound while running the web app locally
I'm trying to run the project available on GitHub locally as mentioned in the instructions but getting ModuleNotFound error even though I've cloned the whole project and following the instruction in a correct way as mentioned. I'm unable to understand this. Please find the repository here. https://github.com/aasis21/4th_umpire -
Pass Image Read From OpenCV From Django To Reactjs and Show it on Website in Real Time
I have python snippet which gets live feed camera video from IP camera: Load each frame using opencv's read function and pass the loaded frame to face detector. Processed frame with bounding boxes received from a function(in a variable). It show the resultant frame using cv2.imshow function. Now my goal is, instead of using opencv's imshow function I want to show it on website in real time as it's working cv2. So now i am using django-react simple application to show it on website. BUT my question is that how we can show the processed image( in variable array) and pass it from django views.py to react and show it on website page. I have googled so many times but couldn't find anything related to this. Thank You. -
How to create an attribute of model which is consists parts of other attributes
Let's I have a model. class Trips(models.Model): from_point = models.CharField(max_length=50) to_point = models.CharField(max_length=50) trip_desc = models.TextField(max_length=250) seats = models.CharField(max_length=20, blank=True, null=True) price = models.PositiveIntegerField() created_time = models.DateTimeField(auto_now_add=True) new_attribure= ? How to create an attribute so when we're creating an instance of Trips it will take part of attributes from_point, to_point + some unique string? For example: obj1 = Trips('Moscow', 'Dushanbe', 'Some_description', '4', '100', 'date_time', 'MosDushUniquestring') In this case it's taking three first characters of from_point, to_point attributes + some unique string. The idea is to have a unique attribute which has some meaning. -
Sort Dictionary of Dictionaries in Django
I have a dataset {6317637: {'name': 'Le Petit Souffle', 'Votes': 314, 'Cuisines': 'French, Japanese, Desserts', 'AverageCostfortwo': 1100, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.8', 'Ratingcolor': 'lightgreen', 'Ratingtext': 'Excellent'}, 6304287: {'name': 'Izakaya Kikufuji', 'Votes': 591, 'Cuisines': 'Japanese', 'AverageCostfortwo': 1200, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.5', 'Ratingcolor': 'lightgreen', 'Ratingtext': 'Excellent'}, 6300002: {'name': 'Heat - Edsa Shangri-La', 'Votes': 270, 'Cuisines': 'Seafood, Asian, Filipino, Indian', 'AverageCostfortwo': 4000, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.4', 'Ratingcolor': 'green', 'Ratingtext': 'Very Good'}, 6318506: {'name': 'Ooma', 'Votes': 365, 'Cuisines': 'Japanese, Sushi', 'AverageCostfortwo': 1500, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'No', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.9', 'Ratingcolor': 'lightgreen', 'Ratingtext': 'Excellent'}, 6314302: {'name': 'Sambo Kojin', 'Votes': 229, 'Cuisines': 'Japanese, Korean', 'AverageCostfortwo': 1500, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.8', 'Ratingcolor': 'lightgreen', 'Ratingtext': 'Excellent'}, 18189371: {'name': 'Din Tai Fung', 'Votes': 336, 'Cuisines': 'Chinese', 'AverageCostfortwo': 1000, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'No', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.4', 'Ratingcolor': 'green', 'Ratingtext': 'Very Good'}, 6300781: {'name': 'Buffet 101', 'Votes': 520, 'Cuisines': 'Asian, European', 'AverageCostfortwo': 2000, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4', 'Ratingcolor': 'green', 'Ratingtext': 'Very Good'}, 6301290: {'name': 'Vikings', 'Votes': 677, 'Cuisines': 'Seafood, Filipino, Asian, European', 'AverageCostfortwo': 2000, 'Currency': 'Botswana Pula(P)', 'HasTablebooking': 'Yes', 'HasOnlinedelivery': 'No', 'Aggregaterating': '4.2', … -
How to save a value for the Get Request Using Views-Models
I am trying to create a chatbot, I want to create a variable(list/dictionary) the one which is one to save my GET Request, I want to access the value of the variable and manipulate it. After some logical operations, I will use a new variable to save a result and print that result on the same page. -
How to add tag field in django?
Here I have some model and this model should have some tags for making it SEO friendly.For this how can i design my model? Any suggestions or help would be appreciated. my model class TourPackage(models.Model): name = models.CharField(max_length=255) package_detail = models.TextField() image = models.ImageField() booking_start = models.DateTimeField() booking_end= = models.DateTimeField() package_start = models.DateTimeField() #how can i save this tag field for seo purpose #tag = models.CharField() -
Converting csv for fixtures
I am unable to convert test data in CSV format using csv2json.py so that I can use the same in fixtures which should have the format pk, model, and then the fields. [ { "pk": 1, "model": "wkw2.Lawyer", "fields": { "school": "The George Washington University Law School", "last": "Babbas", "firm_url": "http://www.graychase.com/babbas", "year_graduated": "2005", "firm_name": "Gray & Chase", "first": "Amr A" } } ] -
I can import matplotlib.pyplot in one file.py but I cannot import it in view.py in django app
I have plot_file.py which has: import matplotlib.pyplot as plt def plot_graph(): squares = [1, 4, 9, 16, 25] plt.plot(squares) plt.savefig('static/img/sqaure_plot.png', bbox_inches='tight') When I run this, it works and saves the file correctly. I am trying to import this function in the views.py within the same app folder in Django. When I put the import statement in the views.py from plot_file.py import plot_graph as pg And save it and try to initiate runserver I get: ModuleNotFoundError: No module named 'matplotlib' Both the files are in the same folder myapp/plot_file.py myapp/views.py I have installed matplotlib using pip3 install matplotlib. I am using MacOS with python3 installed later. I am using Sublime Text which is compiling on Python3. I do not understand how I can import matplotlib in plot_file.py and not in the views.py file? Beginner here. Thank you in advance. -
Connection.commit() does not persist data in Django Test
I am attempting to test if my db_insert() method works. def db_insert(data, insert_query, limit=100): """Persist data to database :param data: Tuple of tuples :param insert_query: String :param limit: Integer """ # Insert / Merge cursor = conn.cursor() try: for i in range(0, int(len(data) / limit) + 1): sliced_data = data[i * limit:i * limit + limit] if sliced_data: cursor.executemany(insert_query, sliced_data) conn.commit() except Exception as e: conn.rollback() raise DBException('ScriptName:db_manager.py,ErrorType:{}Impact:Unable to insert into database,' 'ErrorMessage:{}'.format(type(e).__name__, e)) This method is called by another method: def insert(cls, new_list): """Insert new data to DB :param new_list: List """ try: insert_query = "insert into TABLE {} values {}" \ .format(tuple(cls.TABLE_ATTR[1:]), ('%s',) * len(cls.TABLE_ATTR[1:])) insert_query = insert_query.replace('\'', '') db_insert(new_list, insert_query) except Exception as e: logger.exception(e) Lastly, the insert() method is invoked in the test case: def test_insert_new_host_iqn_mapping(self): SomeModule.insert(['text1', 'text2', 'text3', 1, settings.SCRIPT_RUN_TIME]) cursor = conn.cursor() cursor.execute("select * from TABLE") data = cursor.fetchall() print(data) # [1] The output in [1] does return 2 tuples. These tuples however are data that have been added into the DB using django models.save() in the setUp(). Can someone show me why the conn.commit() is not persisting the data into the database as expected in a real run? -
Create a model instance with InlinePanel
do you have any idea how can I create an instance of the model by using InlinePanel I do not want to add an existing already one instance but I want to create a new one along with the ParentalKey in my case, the ParentalKey is the family and the person is the ForeignKey @register_snippet class Family(ClusterableModel): title = models.CharField(verbose_name=_("family title"), max_length=100) panels = Page.content_panels + [ InlinePanel("persons", label=_("Persons")), ] class FamilyPerson(Orderable): person = models.ForeignKey("crm.Person", on_delete=models.CASCADE) family = ParentalKey( "crm.Family", on_delete=models.CASCADE, related_name="persons" ) @register_snippet class Person(models.Model): SEX_CHOICES = [("M", _("Male")), ("F", _("Female"))] title = models.CharField(verbose_name=_("person title"), max_length=100) age = models.PositiveIntegerField( verbose_name=_("age") ) sex = models.CharField( max_length=12, choices=SEX_CHOICES ) -
clusterize.js with django; static files not found
I am trying to use the https://clusterize.js.org/ javascript package with my Django website for displaying extremely large tables neatly and speedily. I downloaded the package's necessary js and css files, and referenced them in the html getting loaded when i visit my site's url: mysite.com/popularify <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <link href="/static/js/clusterize.css" rel="stylesheet"> <script src="/static/js/clusterize.min.js"></script> </head> And ensured that I have the two files in that location, but am getting these errs in console when I run the site: My settings.py Django file has : STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] -
How to solve the ConnectionRefusedError: [WinError 10061] the target machine actively refused it? (Django SMTP)
I have read many solution tried to implement but no luck.Please suggest to fix this issue and below are the things implemented in my code. values passed in .env [EMAIL] IP = 10.29.15.9 PORT = 25 FROM = x@y.com In settings.py file import configparser config = configparser.ConfigParser() config.read_file(open(r'.env')) In views.py file s = smtplib.SMTP('10.29.15.65', '25') print("printing s dict",s.__dict__) s.ehlo() #s.sendmail(config.get('EMAIL', 'FROM'), to_email.email, msg.as_string()) s.sendmail("a@b.com", 'c@d.com', msg.as_string()) print("printing the S object", s.__dict__) s.quit() Output I am getting: Using windows platform, i don't have admin rights, Firewall is disabled. -
Django HTMLCalendar Previous and Next Month won't show
I am quite new to Django and am currently building an app to display a calendar using Django. I've been following the tutorial here but I can't make the previous and next month button to work. When I go to http://127.0.0.1:8000/calendar I can see this month's calendar, but when I press previous / next month nothing happens, only the url changes to http://127.0.0.1:8000/calendar/?month=[this_year]-[this_month+/-1] Here is my View Class: class CalendarView(generic.ListView): model = Event template_name = 'calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) d_obj = get_date(self.request.GET.get('day', None)) cal = Calendar(d_obj.year, d_obj.month) html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) d_obj = get_date(self.request.GET.get('month', None)) context['prev_month'] = prev_month(d_obj) context['next_month'] = next_month(d_obj) return context def get_date(req_day): if req_day: year, month = (int(x) for x in req_day.split('-')) return datetime(year, month, day=1) return datetime.today() def prev_month(d_obj): first = d_obj.replace(day=1) prev_month = first - timedelta(days=1) month = 'month=' + str(prev_month.year) + '-' + str(prev_month.month) return month def next_month(d_obj): days_in_month = calendar.monthrange(d_obj.year, d_obj.month)[1] last = d_obj.replace(day=days_in_month) next_month = last + timedelta(days=1) month = 'month=' + str(next_month.year) + '-' + str(next_month.month) return month I'm using Django 2.2 so I did a few changes to the urls: urlpatterns = [ path('calendar/', views.CalendarView.as_view(), name='calendar') ] And this is the body part of the … -
Loading Data from an external API into Django models advice
This is more of a design than technical question. What i am doing is trying to present external API data to a user in the form of a table. The data is a list of products (description, price, etc). The user can select the products that they would like to buy from the table (i.e: select the rows in the table) and then proceed to the next page where a table of only the products they have selected is show. (its almost like an ecommerce cart but instead of adding items one-by-one, multiple items can be added at once. ) The API of available products is always changing and growing as new products are added, also the products are one-offs, as in there is only 1 of them and a second user can not select a product once somebody else has chosen it. At the moment i can do this, however it is all on the client side because i am using Ajax to pass the JSON object straight into the html table. From there I use Jquery and javascript to select the table rows by class toggling and complete the process. (It is very 'hacky'). However, doing it this … -
How to set up logging in Elastic Beanstalk for Django app?
I can't get logging to work on my Django app, running on Elastic Beanstalk. Settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": {"format": "%(asctime)s %(levelname)s %(module)s: %(message)s"} }, "handlers": { "django": { "level": "INFO", "class": "logging.FileHandler", "filename": "/opt/python/log/django.log", "formatter": "verbose", } }, "loggers": { "django": {"handlers": ["django"], "level": "INFO", "propagate": True} }, } If I change log level to DEBUG, there will be lots of action in the logs, but still it won't contain logger.info() or logger.debug() calls. .ebextensions/logging.config: commands: 01_create_file: command: touch /opt/python/log/django.log 02_change_permissions: command: chmod g+s /opt/python/log/django.log 03_change_owner: command: chown wsgi:wsgi /opt/python/log/django.log How I use the logging: import logging logger = logging.getLogger("django") logger.info("Testing") When I run the app locally, logs are successfully sent to console using the following setup: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, } -
Elastic Beanstalk doesn't deliver all environment variables to application
I'm running a Django app on Elastic Beanstalk. Previous version of my app had 11 environment variables in Elastic Beanstalk and worked fine. Latest version requires two more. I have spent several hours wondering why the app doesn't work anymore, before noticing that two environment variables do not exist in os.environ! One of the missing variables is a new variable added today, and the other one worked earlier. Second new variable can be found in os.environ. Length of the variables don't come close to the maximum of 4 KB. How is this possible? -
I want to pass json data from my template to my view
I am trying to pass a JSON object from a JavaScript function to a django view. I am a beginner in django and do not have any idea how to do this. in the template create_proposal.html I have a javascript function called convertToJson that looks like: function convertToJson() { console.log("convert"); var obj = $(".input-form").serializeToJSON({ }); var jsonString = JSON.stringify(obj); } and in my views.py file the function i am trying to receive the json object looks like: def resultPage(request): return render(request, 'result.html') I am trying to pass the jsonString variable in the javascript function to the python function resultPage in the views.py. Thanks in advance. -
How to connect MongoDB with django?
Hello i am using mysql as my primery database in Django but now i want to use MangoDB as my database. I want to know how to connect MongoDB in Django. -
'authapp' is not a registered namespace
Error Message 'authapp' is not a registered namespace I created Django an app in DJango and named it authapp. Root app name is practise 1 and inner app name is authapp. Below is the directory structure. Settings file code INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'authapp' ] Inside the inner app, the views.py code is below. from django.shortcuts import render def login(request): if(request.method == "POST"): return render(request, 'login1.html') else: return render(request, 'login.html') Below is the code in login template inside authapp. <form method="post" action="{% url 'authapp:login' %}"> {% csrf_token %} <input type="text" name="email" class="form-control"> <input type="password" name="password" class="form-control"> <button type="submit" class="btn btn-primary"> Login </button> </form> Am I missing anything? Edit 1 Below is code in urls.py from django.contrib import admin from django.urls import path, include from .import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('authapp.urls')), path('', views.home) ] -
Unable to access "uwsgi" gateway in Docker
I want to deploy a Django project in Kubernetes. Right now I'm creating a docker image to understand the project. Dockerfile FROM python:3.7 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip3 install -r requirements.txt docker-compose.yml version: '3' services: mysql: image: mysql:5.7 volumes: - ./mysql:/var/lib/mysql expose: - "3306" restart: always environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=nlpapp - MYSQL_USER=root - MYSQL_PASSWORD=root nginx: image: nginx:alpine volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf - ./nginx/conf:/etc/nginx/conf.d - ./web/staticfiles:/django_static ports: - "80:80" depends_on: - web redis: image: redis:alpine expose: - "6379" restart: always web: build: . command: uwsgi --ini uwsgi.ini working_dir: /code/blog volumes: - .:/code expose: - "8000" depends_on: - mysql - redis celery: build: . command: celery -A blog worker -l info working_dir: /code/blog volumes: - .:/code depends_on: - mysql - redis uwsgi.ini [uwsgi] socket=:8000 chdir=/code/blog module=blog.wsgi:application pidfile=/tmp/blog-master.pid master=True vacuum=True processes=1 max-requests=5000 These are the main files. when I'm going to start docker-compose up command on that time MySQL, Redis, nginx, celery containers are working properly but WSGI(web) container is not running and showing an error. ERROR: for web Cannot start service web: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: \"uwsgi\": executable file not found in $PATH": unknown ERROR: Encountered errors while bringing up the … -
Use a loader till the page fully loads in Django GET call
I have a URL which fetches some large collection of data and shows in the front django template , but some times loading this data takes a lot of time, so i need to a show a loader till the page completely loads. I can see many solutions related to this questions, but all of them are handling POST call, but in my case its a GET call, For example, URL: /students/list/ class ListRecords(View): """ This class is used to list all the students record """ def __init__(self): self.data = self.get_records() def get(self, request, *args, **kwargs): return render(request, 'list.html', {'data': data_obj}) So how can i show a loader till the page completely loads in list.html, is there any effective and easy way to implement the same. Any help would be greatly appreciated. Thank you.. -
Hosting django on aks behind nginx-ingress
I am trying to host a django website on Azure kubernetes service behide nginx-ingress, and I would like my django web show under a path. e.g. when access the default admin site, I would like to access it at http://example.com/django/admin instead of http://example.com/admin I tried the configure below, when I access http://example.com/django/admin it will forward me to http://example.com/admin and show me 404 error from default ingress backend, as I set django debug to ture I assume this mean ingress did not send my request to my django service apiVersion: extensions/v1beta1 kind: Ingress metadata: name: django-ingress labels: app: django namespace: default annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/ssl-redirect: "false" nginx.ingress.kubernetes.io/rewrite-target: /$2 spec: rules: - http: paths: - backend: serviceName: django-service servicePort: 80 path: /django(/|$)(.*) so I try to curl -I -k http://example.com/django/admin, and it show something like below HTTP/1.1 301 Moved Permanently Server: openresty/1.15.8.2 Date: Wed, 06 Nov 2019 04:14:14 GMT Content-Type: text/html; charset=utf-8 Content-Length: 0 Connection: keep-alive Location: /admin/ The same thing happen to any valid page in the site, if I curl -I -k http://example.com/django/any_valid_page it show below: HTTP/1.1 301 Moved Permanently Server: openresty/1.15.8.2 Date: Wed, 06 Nov 2019 04:14:14 GMT Content-Type: text/html; charset=utf-8 Content-Length: 0 Connection: keep-alive Location: /any_valid_page/ I wonder … -
Django loop all existing record to save but only one record save
this is my code in html <tr> <td colspan="2" style="text-align: center;"> <h2 style="font-weight: bold;">Required Documents:</h2> </td> </tr> {% for d in doc %} <tr> <td style="text-align: left;"> <input type="file" name="myfile-{{d.id}}" value="{{d.id}}" style="outline: none;" required/> {{d.id}}{{d.Description}} </td> <td></td> </tr> {% endfor %} views.py def enrollmentform(request): id = request.GET.get('StudentID') students = StudentProfile.objects.all().filter(id=id) doc = DocumentRequirement.objects.all().filter() return render(request, 'accounts/EnrollmentForm.html', {"doc": doc}) this is my logic on how to save my record myfile = request.FILES['myfile-6'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) V_insert_data = StudentsEnrollmentRecord( Student_Users=studentname, Payment_Type=payment, Education_Levels=educationlevel, School_Year=schoolyear ) insert_doc = StudentsSubmittedDocument( Students_Enrollment_Records = V_insert_data, Document = myfile ) insert_doc.save() I don't have idea on how to loop this myfile = request.FILES['myfile-6'] with the existing id of Table Documents. please help me guys, im stuck on this problem 3days for example if the student comply the 4 required documents it will save like this correct in my case it save only 1 record, wrong saving -
Showing model entries as a form in a table
I have a model which has data that i need to show to a user in the form of a table. The user can select rows in the table and then proceed to the next page with only those items. I think the way to do this with django is to crate a table where every row is a form, when a user clicks on a row it updates the status of that entry in the table to be "Selected" and when the user proceeds to next page, a new queryset with only entries with a status of "Selected" are shown. Does this make sense? Or is there a better way to achieve this? -
How could I retrieve data from mysql in django to be shown in a modal wherein I could also update it?
What I needed to do is after clicking the view modal button, it will show the information and then there is a button also wherein could update it. Models.py class Employee(models.Model): first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) middle_name = models.CharField(max_length=100, blank=True, null=True) userid = models.CharField(max_length=45, blank=True, null=True) email_address = models.CharField(max_length=100, blank=True, null=True) I dont have views.py yet( Dont know where to start) MySQL DB