Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make query to filter data from database table in Django?
There are three tables which are: models.py class Student(models.Model): gen_choices = ( ("Male", "Male"), ("Female", "Female"), ("Third", "Third"), ) enrollNo = models.IntegerField(default=add_one) fname = models.CharField(validators=[max_len_check], max_length=26) lname = models.CharField(validators=[max_len_check], max_length=26) gender = models.CharField(max_length=6, choices=gen_choices) dob= models.DateField() address = models.CharField(max_length=256) email = models.EmailField() mobile = models.BigIntegerField() status = models.BooleanField(null=True) userID = models.OneToOneField(User, on_delete=models.CASCADE) image = models.FileField(upload_to="stdimages/", null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Entexaminfo(models.Model): entexamses = ( ("June Session", "June Session"), ("December Session", "December Session"), ) approve_choice = ( ("Pending", "Pending"), ("Accepted", "Accepted"), ("Rejected", "Rejected"), ) ename = models.CharField(max_length=16, choices=entexamses) enrollno = models.OneToOneField(Student, on_delete=models.CASCADE) #programs = models.ManyToManyField(Programs, related_name='proNames', default=0) program = models.ManyToManyField(Programs, default=0) center = models.ForeignKey(Excenter, on_delete=models.CASCADE) remarks = models.CharField(validators=[max_len_check], max_length=256, default="-") #status = models.BooleanField() status = models.CharField(max_length=8, choices=approve_choice, default="Pending") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager # for admin pannel to display for correction def __str__(self): return self.ename class Ex_schedule(models.Model): exDate = models.DateField() exTime = models.TimeField() exDuration = models.CharField(validators=[max_len_check], max_length=26) programs = models.OneToOneField(Programs, on_delete=models.CASCADE) exRemarks = models.CharField(max_length=256, null=True) exStatus = models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager # for admin pannel to display for correction def __str__(self): return self.exDate class Programs(models.Model): proName = models.CharField(validators=[max_len_check], max_length=26) proDuration =models.CharField(validators=[max_len_check], max_length=26) proFees = models.IntegerField(null=True) proDetails = models.CharField(validators=[max_len_check], … -
How do I solve this error even though I add {% csrf_token %}
I'm having trouble adding a new add-post when I have checked out all entries. This error appears THIS IS HTML ADD POST : -
unable to fetch data from sqlite database to html page
I am Shoaib I am a student I am facing problem in my project the problem is that I was unable to fetch data from database to html page how can I fix the error I tried to fix it many times by it's not fixings dskjkds jksdkdskl jdfskjlkdsfjlkdfsf jdsfjkljdsl;kjdsafjksjdkfaksdf ds jsdjjk sdjhsd here is my views.py from django.shortcuts import render, redirect from .models import GeeksModel # Create your views here. def first(request): student = GeeksModel.objects.all() return render(request, 'student/1.html', {student : 'student'}) here is my models.py from __future__ import unicode_literals from django.db import models # Create your models here. class GeeksModel(models.Model): admission = models.IntegerField(unique=True) name = models.CharField(max_length=50) english = models.IntegerField() hindi = models.IntegerField() maths = models.IntegerField() science = models.IntegerField() def __str__(self): return self.name here my HTML page {% extends 'admin/adminbase.html'%} {% block content %} <div id="layoutSidenav_content"> <main> <div class="container-fluid"> <h1 class="mt-4">Tables</h1> <ol class="breadcrumb mb-4"> <li class="breadcrumb-item"><a href="/panel">Dashboard</a></li> <li class="breadcrumb-item active">Tables</li> </ol> <div class="card mb-4"> <div class="card-header"> <i class="fas fa-table mr-1"></i> DataTable </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Admission No.</th> <th>Science</th> <th>English</th> <th>Hindi</th> <th>Maths</th> <th>action</th> </tr> </thea> <tbody> <tr> <td>{{ student.id }}</td> <td>{{ student.admission }}</td> <td>{{ student.name }}</td> <td>{{ student.science }}</td> <td>{{ … -
if request.method == "POST" return false
When sending a POST request to the following views.py request.method == "POST" return false value title = 'Update' posts = get_object_or_404(post, id=id) form = postForm(request.POST or None, request.FILES or None, instance=posts) author = get_Author(request.user) print(request.FILES == "POST") print(form.errors) if request.method == "POST": if form.is_valid(): form.instance.author = author form.save() return redirect(reverse("postPage", kwargs={ 'id' :form.instance.id }))``` -
How load json data to table faster django
I have created a web request to get the data into json format and then parsed it to load to a database table as below: def loaddata(request): if request.method == "POST": url = 'apiurl' response = requests.get(url,stream=True) data = response.json() for i,item in enumerate(data): records = Model.objects.create( empl = data.get('empl',None), name = data.get('empl',None).get('name',None)) records.save() return render(request,"main.html") This currently processes data record by record which makes it super slow. I have also read in the below url that this can be done easily with sql batch insert. http://stefano.dissegna.me/django-pg-bulk-insert.html referring specifically to the section described as below: SQL batch INSERT We can do a lot better by building a single SQL INSERT statement to create multiple records at once, similar to the SQL built by bulk_create: import utils from contextlib import closing from django.db import connection from django.utils import timezone def sql_batch_insert(n_records): sql = 'INSERT INTO app_testmodel (field_1, field_2, field_3) VALUES {}'.format( ', '.join(['(%s, %s, %s)'] * n_records), ) params = [] for i in xrange(0, n_records): params.extend([i, str(i), timezone.now()]) with closing(connection.cursor()) as cursor: cursor.execute(sql, params) if name == 'main': utils.timed(sql_batch_insert) Building the SQL query manually adds more noise to the code than using bulk_create, but other than that it has no … -
How to avoid 1 as boolean value in django template (1 is taking as boolean value Ture)?
My view is returning a dictionary. **{'id': 1, 'user_info_id': 1, 'coding': False, 'testing': False, 'req_analysis': True}** In Django template, I want to print all the keys of value == True. I have written the below code in Django template. {% for key, value in db_data.0.items %} {% if value == True %} {{ key }} {% endif %} {% endfor %} But, in output, I am getting key with value True as well as the keys with value 1. O/P : id user_info_id testing I want output as "testing" only. Can anyone please help me with this. -
Use django-filter for filtering in graphene-django without relay
I'm working on a GraphQL project that uses graphene-django. Given the following, how can I filter queries with the custom filterset I defined (without relay): filters class SomeFilterSet(FilterSet): class Meta: model = models.SomeModel fields = [ 'field_one', 'field_two', 'field_three' ] types class SomeType(DjangoObjectType): class Meta: model = models.SomeModel filterset_class = SomeFilterSet class SomePaginatedType(graphene.ObjectType): page = graphene.Int() pages = graphene.Int() has_next = graphene.Boolean() has_prev = graphene.Boolean() objects = graphene.List(SomeType) utils def get_paginator(qs, page_size, page, paginated_type, **kwargs): p = Paginator(qs, page_size) try: page_obj = p.page(page) except PageNotAnInteger: page_obj = p.page(1) except EmptyPage: page_obj = p.page(p.num_pages) return paginated_type( page=page_obj.number, pages=p.num_pages, has_next=page_obj.has_next(), has_prev=page_obj.has_previous(), objects=page_obj.object_list, **kwargs ) schema class Query(graphene.ObjectType): some_field = graphene.Field( SomePaginatedType, id=graphene.ID(required=True), page=graphene.Int() ) @login_required def resolve_some_field(self, info, id, page): try: var_name = models.SomeModel.objects.get(pk=id) except models.SomeModel.DoesNotExist: return GraphQLError('SomeModel does not exist') else: page_size = PAGE_SIZE qs = var_name.attribute.all() return get_paginator( qs, page_size, page, SomePaginatedType) query query { someField(id: 1) { page pages hasNext hasPrev objects { id fieldOne fieldTwo } } } The above works as expected. However, when I try to filter by one of the fields defined in the filterset class, I get the error: Unknown argument "fieldOne" on field "objects" of type "SomePaginatedType". Here's how I tried to filter: … -
Django Jquery preventDefault() does not work
I am trying to submit a textfield using Ajax. This is the form <form id = "msgform" method="POST" > {% csrf_token %} <textarea id = "msg" name = "msg" > </textarea> <button type="submit" >Send</button> </form> Here is the Jqeury and Ajax code that is supposed to prevent the default form submission and submit the ajax. $(document).on('submit', '#msgform', function(e){ e.preventDefault(); return false; $.ajax({ type:'POST', url:'{{request.path}}', data:{ value:$('#msg').val(), csrfmiddlewaretoken: '{{ csrf_token }}', }, success:function(){ } }) }) In my view.py I have a variable set equal to request.POST['value'] but the program is unable to find the value because the Ajax form does not run. However, if I set the var = to request.POST['msg'] (The var for default submission) it works fine. Why is the default submission still occurring and how do I stop it? -
How to get or update in a form?
What I am trying to do : I am trying to update the LogDone object in my view when the form is save. The logdone was already created before, I want to use the id of the logdone previously created and update instead of creating a new one. def create_logdone(request, logmessage_id, log_id, token ): log = get_object_or_404(LogBook, pk=log_id) logmessages = get_object_or_404(LogMessage, pk=logmessage_id, logbook=log) logdone = LogDone.objects.update_or_create(logmessage=logmessages) form = CreateLogDone(request.POST) if request.method == "POST": if form.is_valid(): instance = form.save(commit=False) instance.done_by = request.user instance.logmessage = logdone instance.save() Error I get "LogDone.logmessage" must be a "LogMessage" instance. -
Django Custom Form Field Property not Available in Template
I'm writing a voting system that shows the number of votes for an option in the form. I have Vote and Option models: class Vote(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=False, null=False) option = models.ForeignKey(Option, on_delete=models.PROTECT, blank=False, null=False) class Option(models.Model): prompt = models.TextField(blank=False, null=False) I wrote a simple custom form field to hold the current number of votes: class VoteField(forms.BooleanField): vote_count = 0 def __init__(self, *args, option, **kwargs): self.vote_count = Vote.objects.filter(option=option).count() super(VoteField, self).__init__(*args, **kwargs) I have a form to create a list of options to vote for: class VoteForm(forms.BaseForm): base_fields = {} def __init__(self, *args, options, user, **kwargs): for options in options: field = VoteField(survey_question=survey_question) field.label = option.prompt self.base_fields["option" + str(option.pk)] = field super(SurveyResponseForm, self).__init__(*args, **kwargs) And I have a template to show the voting form: {% for field in form %} <div class="row"> <div class="col"> {{ field }} </div> <div class="col"> {{ field.label }} </div> <div class="col"> {{ field.vote_count }} </div> </div> {% endfor %} I populated the db with an option and some responses. In the shell it works as expected: >>> option = Option.objects.get(pk=1) >>> vote_field = VoteField(option=option) >>> vote_field.vote_count 3 However, my template outputs nothing where I say to print vote_count: <div class="row"> <div class="col"> <input type="checkbox" … -
cannot manipulate a dictionary data from Django inside the template
in my view.py: from django.shortcuts import render # Create your views here. def home(req): a={'a':1,'c':5} return render(req,'index.html',{'a':a}) in my template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <!-----Server data-----> <body> <p>{{a['a']}}</p> </body> </html> it gives me a template error, why i can't subscript the dic? -
Django CSRF Cookie not set for Chrome, Safari but not Firefox
I have recently moved to a new computer. My Django project works fine on the old computer. Running the same code on the new one I find that I get "CSRF Verification Failed" when logging in. This gives message in the log of 'CSRF cookie not set.'. This happens when using Chrome and Safari but it works find with Firefox. When I inspect they all have the hidden input for `csrfmiddlewaretoken' but when I look at storage in the browser inspector the cookie is only set in Firefox. I am at a loss as I've changed nothing in the code and it works fine on my old laptop. Any suggestions would be greatly received. -
Django static files (base dir moved to another folder)
so what happened is that i put my project folder called ecommerce inside another folder called ecommerce_project and now all the modifications i did in my css files are not showing only the previous style are showing (before i moved ecommerce to ecommerce_project) this my settings : STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(VENV_PATH, 'static_root') MEDIA_ROOT = os.path.join(VENV_PATH, 'media_root') how do i fix that ?? thank you -
Grant users from CloudSQL instance IAM permissions to Cloud Storage objects
I have a question about GCP and this Django app I am making. I am using Google cloud storage to hold documents that I need to provide access permissions for to my users, but I can't think of how to link users from my app (being saved to CloudSQL-PostgresSQL) to my Google Cloud project. This feels like it should be an easy case to handle, but i'm used to services like Cognito handling this for me. Should I make a service account for every user? -
DetailView class not showing data
I'm using this test project to learn django, the problem is taht the view is not showing the data, and I'm not sure how to pass the data to a detailview class this is the model class Empleado(models.Model): departamento = models.ForeignKey(Departamento, on_delete=models.CASCADE) habilidades = models.ManyToManyField(Habilidad) nombre = models.CharField(max_length=40) fecha_nacimiento = models.DateField() antiguedad = models.IntegerField(default=0) def __str__(self): return f"nombre = {self.nombre}, fecha de nacimiento = {self.fecha_nacimiento}, antiguedad = {self.antiguedad}" the view class EmpladoDetailView(DetailView): model = Empleado template_name = 'empleados.html' def get_context_data(self, **kwargs): context = super(EmpladoDetailView, self).get_context_data(**kwargs) context['titulo'] = 'Detalles Empleado' return context and the view {% extends 'base.html' %} {% block contenido %} <table> {% for empleado in lista_empleados %} <tr> <td>ID</td> <td>{{empleado.id}}</td> </tr> <tr> <td>Nombre</td> <td>{{empleado.nombre}}</td> </tr> <tr> <td>Antiguedad</td> <td>{{empleado.antiguedad}}</td> </tr> {% endfor %} </table> {% endblock contenido %} It seems like the model data is not arriving to the view but I don't know what I missed -
Django : list into serializer
I would like to create rest API with Django. I heard about serializers in Django Rest Framework : from rest_framework import serializers. Next, I have to create some sort of models. I want to create a JSON response of this type : { id: "489", state: "PREPARATION", orderDay: "2020-06-24", deliveryDay: "2020-06-30", deliveryAddress: "Place des Fêtes", comment: "", // facultatif products: [ { id: "420", name: "Côte de boeuf", price: "28.90", oldPrice: "", // facultatif unit: "KG", categoryId: "69666", byProducts: [ { id: "420161", name: "unité", quantity: 42, }, ], }, ], } So I have to add a list into my serializers model (products, byProduct). Can I do this with serializers and how ? Thanks by advance -
error trying to install django on a virtual environment using vs code but i get errors
so im trying to learn django and searched for a way to install it and it says that its better to create a virtual environment instead of installing it globally,so i installed pipenv fine but when i tried to install django in pipenv it gave me this error and i cant find any answers in any other existing posts Instalation of pipenv: PS C:\Users\max25\Desktop\Python\learning_frameworks.py> pip install pipenv Requirement already satisfied: pipenv in c:\users\max25\appdata\local\packages\pythonsoftwarefoundation.python.3.8_qbz5n2kfra8p0\localcache\local-packages\python38\site-packages (2020.6.2) Requirement already satisfied: virtualenv in c:\users\max25\appdata\local\packages\pythonsoftwarefoundation.python.3.8_qbz5n2kfra8p0\localcache\local-packages\python38\site-packages (from pipenv) (20.0.25) Requirement already satisfied: virtualenv-clone>=0.2.5 in c:\users\max25\appdata\local\packages\pythonsoftwarefoundation.python.3.8_qbz5n2kfra8p0\localcache\local-packages\python38\site-packages (from pipenv) (0.5.4) Requirement already satisfied: certifi in c:\users\max25\appdata\local\packages\pythonsoftwarefoundation.python.3.8_qbz5n2kfra8p0\localcache\local-packages\python38\site-packages (from pipenv) (2020.6.20) Requirement already satisfied: pip>=18.0 in c:\users\max25\appdata\local\packages\pythonsoftwarefoundation.python.3.8_qbz5n2kfra8p0\localcache\local-packages\python38\site-packages (from pipenv) (20.1.1) Requirement already satisfied: setuptools>=36.2.1 in c:\program files\windowsapps\pythonsoftwarefoundation.python.3.8_3.8.1008.0_x64__qbz5n2kfra8p0\lib\site-packages (from pipenv) (41.2.0) Requirement already satisfied: distlib<1,>=0.3.0 in c:\users\max25\appdata\local\packages\pythonsoftwarefoundation.python.3.8_qbz5n2kfra8p0\localcache\local-packages\python38\site-packages (from virtualenv->pipenv) (0.3.1) Requirement already satisfied: appdirs<2,>=1.4.3 in c:\users\max25\appdata\local\packages\pythonsoftwarefoundation.python.3.8_qbz5n2kfra8p0\localcache\local-packages\python38\site-packages (from virtualenv->pipenv) (1.4.4) Requirement already satisfied: filelock<4,>=3.0.0 in c:\users\max25\appdata\local\packages\pythonsoftwarefoundation.python.3.8_qbz5n2kfra8p0\localcache\local-packages\python38\site-packages (from virtualenv->pipenv) (3.0.12) Requirement already satisfied: six<2,>=1.9.0 in c:\users\max25\appdata\local\packages\pythonsoftwarefoundation.python.3.8_qbz5n2kfra8p0\localcache\local-packages\python38\site-packages (from virtualenv->pipenv) (1.15.0) Error after trying to install django in pipenv PS C:\Users\max25\Desktop\Python\learning_frameworks.py> pipenv install django pipenv : The term 'pipenv' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was … -
Django admin panel error when update a post "'bytes' object has no attribute '_committed'"
I want to create a inventory system. In this system admin can add medicine to database. I used admin panel for that. So, I add/delete/update the medicine from django admin panel only. I can add or delete a medicine easily but when I try update it, there is an error: AttributeError at /admin/medicines/medicine/18/change/ 'bytes' object has no attribute '_committed' How can I fixed it? models.py from django.db import models from ckeditor.fields import RichTextField from django.urls import reverse from django.utils.text import slugify class Medicine(models.Model): medicine_name = models.CharField(max_length=100) medicine_info = RichTextField(verbose_name="notes") medicine_code = models.CharField(max_length=100) medicine_qr = models.CharField(max_length=100) medicine_price = models.IntegerField() medicine_stock = models.IntegerField() medicine_image = models.ImageField(upload_to='img_medicine', null=True, blank=True) slug = models.SlugField(max_length=100, unique=True, editable=False) def get_image(self): if self.medicine_image and hasattr(self.medicine_image, 'url'): return self.medicine_image.url else: return def __str__(self): return self.medicine_name class Meta: ordering = ['medicine_name'] def get_create_url(self): return reverse('medicines:medicine_create', kwargs={'slug': self.slug}) def get_unique_slug(self): slug = slugify(self.slug.replace('ı', 'i')) unique_slug = slug counter = 1 while Medicine.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, counter) counter += 1 return unique_slug def get_absolute_url(self): return reverse('medicines:medicine_create', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): self.slug = self.get_unique_slug() return super(Medicine, self).save(*args, **kwargs) forms.py class MedicineForm(ModelForm): class Meta: model = Medicine fields = [ 'medicine_name', 'medicine_info', 'medicine_code', 'medicine_price', 'medicine_stock', 'medicine_image', ] traceback Environment: Request Method: POST … -
Can't submit Ajax post in django. MultiValueDictKeyError
I have an HTML document with a textarea <form id = "msgform" method="POST" > {% csrf_token %} <textarea id = "msg" name = "msg" > </textarea> <button type="submit" >Send</button> </form> And I have an Ajax form submission $(document).on('submit', '#msgform', function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'{% url "group" %}', data:{ value:$('#msg').val(), csrfmiddlewaretoken: '{{ csrf_token }}', }, success:function(){ } }) } When I try to submit text, the program can't find the variable "value" even though I declared it. It says, MultiValueDictKeyError. What am I doing wrong? -
Django CMS - Unable to modify structure of a newly added webpage
I'm completely new to Django CMS and I'm stuck with this issue. I have added a new module to an existing Django project and created a new Html page. This is the templates configuration in settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'site_cms', 'templates'), ], 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.template.context_processors.csrf', 'django.template.context_processors.tz', 'sekizai.context_processors.sekizai', 'django.template.context_processors.static', 'cms.context_processors.cms_settings', 'core.context_processors.request_info', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'django.template.loaders.eggs.Loader' ], }, }, ] In the new page, I'm extending the home page of the website as I've seen other pages do. This is the home page home.html (/core/templates/core/home.html): {% load i18n easy_thumbnails_tags static %} <!DOCTYPE html> <html lang="en"> <head> {% load staticfiles i18n menu_tags%} </head> <main> <div class="container"> {% block content %} This is my new page newpage.html (/newpage/templates/newpage/newpage.html) {% extends "home.html" %} {% load easy_thumbnails_tags i18n static core_filters bootstrap4 %} {% block content %} {% load bootstrap4 %} <div class="container"> After creating the new page, I added it to the website main-menu through the Django CMS bar. I selected the template for the page to the one the parent (home) uses. I see this makes changes only in Database. OK, so now I have this page in the main-page … -
How to change data-level class in template based on the if condition?
Here I want to change the data-level in my template based on the skill status. I am iterating the skill objects in template and while doing that if the first condition matches then in all skills the first data-level value applies but doesn't check for other conditions. How can I change the data-level value based on the each skill status ? models class Skill(models.Model): status = ( (0, 'Beginner'), (1, 'Good'), (2, 'Expert'), (3, 'Pro'), ) name = models.CharField(max_length=255) status = models.IntegerField(choices=status) views skills = Skill.objects.order_by('-status') data_level = 0 for skill in skills: print(skill.status) if skill.status == 0: data_level = 20 if skill.status == 1: data_level = 45 if skill.status == 2: data_level = 70 if skill.status == 3: data_level = 9 context = { 'skills': skills, 'data_level':data_level} template {% for skill in skills %} <div class="item"> <h3 class="level-title">{{skill.name}}</h3> <div class="level-bar-inner" data-level="{{data_level}}%"> </div> {% endfor %} -
Django Celery: Task never executes
In my django application I am using celery. In a post_save signal, I am updating the index in elastic search. But for some reason the task gets hung and never actually executes the code: What I use to run celery: celery -A collegeapp worker -l info The Signal: @receiver(post_save, sender=University) def university_saved(sender, instance, created, **kwargs): """ University save signal """ print('calling celery task') update_university_index.delay(instance.id) print('finished') The task: @task(name="update_university_index", bind=True, default_retry_delay=5, max_retries=1, acks_late=True) def update_university_index(instance_id): print('updating university index') The only output I get is calling celery task. after waiting over 30 minutes, it doesn't ever get to any other print statements and the view continue to wait. Nothing ever shows in celery terminal. -
Do we need to render templates when using ReactJS as a front-end?
So I just created a website's front-end using ReactJS. Now all I need is a backend database that I will fetch data from using requests. The question is whether I need to render templates using my backend or just use my server to make requests (eg get, post etc) PS. I will be using Django as my backend. Thank you everyone who will help me out. -
Having trouble adding apps into my django project
I've been trying to richen my text field in my Django project. I've tried different text-editors. At first I thought it was a problem within tinymce but then I realized it was a general issue. Even though I do all the steps as shown -installing the app, adding 'blabla' into INSTALLED_APPS, importing certain things in need etc.- terminal always ends up not being able to find the module. I'm pretty sure it's a 2-minute fix but I haven't found any solutions yet. The modules are downloaded like mentioned. Every file in the project is in its place. This is the exact response I get: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/user/.pyenv/versions/3.7.3/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/user/.pyenv/versions/3.7.3/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/Users/user/.pyenv/versions/3.7.3/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/user/.pyenv/versions/3.7.3/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/user/.pyenv/versions/3.7.3/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Users/use/.pyenv/versions/3.7.3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'ckeditor' -
Django send urls to frontend
I am working on a Django project that is serving templates containing ReactJs mini apps. The structure is like this: url "/" loads template "homepage.html" that just loads "homepage.js" url "/someapp/" loads template "someapp.html" that just loads "someapp.js" My urls.py file has quite a lot of routes that I have to pass into the frontend side. The first thing that I would do is to just throw the urls into the template and build a global js object. Does Django has anything that could be of help in this case?