Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Post request causes "django.db.models.query_utils.DeferredAttribute" DRF
I'm quite new at this so patiance please. Now what I was trying to do was, create a function that checks if there are any objects in the database, if there are increase the counter, give that value to a model field and then pass that value to a field on another model. I tried do it as best as I could and when I run a post method, it does post the data, so if I were to check it out on the database, the field which I supposedly update gives me the error django.db.models.query_utils.DeferredAttribute Edit: If i run the code once, as I said it does create the object and the field has that error from above, if I try to make another post request, it crashes and gives the error that the field is supposed to be unique but it isn't. This is my simplified code below, if you need to see more just ask. Thanks in advance. class Order(models.Model): code = models.CharField(max_length=10, unique=True) code_year = models.IntegerField def __str__(self): return str(self.code) def save(self, *args, **kwargs): self.code = Counter.name super(Order, self).save(*args, **kwargs) class Counter(models.Model): def count(self): self.value=0 items = Order.objects.all() for item in items.values('code_year'): self.value+=1 return self.value @property … -
fetching data with datatable js django ajax , lose data when searching
i'm trying to fetching data using ajax , and display data into datatable showing data is working fine , but when i try to search or doing some sort into the datatable , it lost the data , and requires to reload the page again ?! class MainGroup(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) main_type = models.CharField(max_length=40,unique=True) date = models.DateTimeField(auto_now_add=True) my views.py def list_maingroup(request): lists = MainGroup.objects.all().order_by('-pk') data = [] for obj in lists: item = { 'id':obj.id, 'admin':obj.admin.username, 'main_type':obj.main_type, 'date':obj.date } data.append(item) return JsonResponse({'data':data}) my templates const form = document.getElementById('main_form') form.addEventListener("submit",submitHandler); function submitHandler(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url 'products:maingroup' %}', data : $('#main_form').serialize(), dataType: 'json', success: successFunction, }); } function successFunction(data) { if (data.success) { form.reset(); alertify.success("added") } else if(data.error_code=='invalid'){ for(var key in data.error_msg){ if(key == 'main_type'){ document.getElementById('main_error').removeAttribute('hidden') document.getElementById('main_error').innerHTML = data.error_msg[key][0] } } } } $.ajax({ type:'GET', url:'{% url 'products:list-maingroup' %}', success:function(response){ console.log(response) data = response.data var k = '<tbody>' for(i = 0;i < data.length; i++){ k+= '<tr>'; k+= '<td>' + data[i]['id'] + '</td>'; k+= '<td>' + data[i]["admin"] + '</td>'; k+= '<td>' + data[i]["main_type"] + '</td>'; k+= '<td>' + data[i]["date"] + '</td>'; k+= '</tr>' } k+='</tbody>' document.getElementById('tableData').innerHTML = k } }) <div class="col-md-12"> <!-- general form elements --> <div … -
Django JsonResponse not returning expected response of JSON
I’m trying to return some json with this: return JsonResponse({"likes": likes}) The response I’m getting is commented in my client.js code, the response doesn’t contain my json and causes an error when trying to parse the response. Why isn't the response json? If json is in the response how do I access it? In views.py: import json from django.http import JsonResponse @csrf_exempt @login_required def like_post(request): if request.method == "POST": data = json.loads(request.body) print("POST request received", data) try: post = Post.objects.get(id=data["post_id"]) except Post.DoesNotExist: pass try: liked = Like.objects.get(user=request.user, post=post) print(liked) except Like.DoesNotExist: print("adding new like") like = Like(user=request.user, post=post) like.save() likes = post.likes.all().count() print("likes", likes) return JsonResponse({"likes": likes}) else: print("like_post accessed via GET") return render(request, "network/index.html") In my client.js: function handleLike(e) { const data = e.target.dataset console.log(e.target, data.post_id, data.post_user, data.user) if (data.post_user !== data.user) { fetch("/posts/like", { method: "POST", body: JSON.stringify({ post_id: data.post_id }) }) .then( res => { console.log(res) /* Response { type: "basic", url: "http://localhost:8000/posts/like", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false } */ JSON.parse(res) // Error SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data }) .then( res => { e.target.firstElementChild.innerText = `(${res.likes})` }) .catch( err => … -
Working with python and django: my Status is not rendering on my views correctly
So my goal is to show the status of the job application as a drop down with the default to 'applied' but the rest of the selection would be: ('A', 'Applied'), ('B', 'In Progress'), ('C', 'Interview scheduled'), ('D', 'Interview complete'), ('E', 'Job Offer'), ('F', 'Incomplete'), ('G', 'Not Selected'), ('H', 'Unknown'), here are my models class Job_application(models.Model): name = models.CharField(max_length=100) company = models.CharField(max_length=100) location = models.CharField(max_length=250) date = models.DateField('Date Applied') url = models.CharField( max_length=250, blank=True ) requirements = models.TextField( max_length=500, blank=True ) notes = models.TextField( max_length=500, blank=True ) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('detail', kwargs={'job_id': self.id}) #every model instance has its own method #django will now render the detail page, class Attachment(models.Model): # will implement later with AWS if possible -CO url = models.CharField(max_length=250) job_app = models.ForeignKey(Job_application, on_delete=models.CASCADE) def __str__(self): return f'Attachment for job_id: {self.job_id} @{self.url}' class Status(models.Model): date = models.DateField('Date') STATUS = ( ('A', 'Applied'), ('B', 'In Progress'), ('C', 'Interview scheduled'), ('D', 'Interview complete'), ('E', 'Job Offer'), ('F', 'Incomplete'), ('G', 'Not Selected'), ('H', 'Unknown'), ) status = models.CharField( max_length=1, choices=STATUS, default=STATUS[0][0] ) job_app = models.ForeignKey(Job_application, on_delete=models.CASCADE) def __str__(self): # Nice method for obtaining the friendly value of a Field.choice return f"{self.get_status_display()}" # change the … -
I'm getting an error that I do not understand from Django
I am trying to follow James Bennett example but getting this error: ValueError at /loadtest too many values to unpack (expected 2) Request Method: GET Request URL: http://127.0.0.1:8000/loadtest Django Version: 3.2.5 Exception Type: ValueError Exception Value: too many values to unpack (expected 2) Exception Location: /Users/lowell.dennis/Code/loadtest/env/lib/python3.9/site-packages/django/forms/widgets.py, line 691, in _choice_has_empty_value Python Executable: /Users/lowell.dennis/Code/loadtest/env/bin/python Python Version: 3.9.6 Python Path: ['/Users/lowell.dennis/Code/loadtest', '/Users/lowell.dennis/.vscode/extensions/ms-python.python-2021.7.1053846006/pythonFiles/lib/python/debugpy/_vendored/pydevd', '/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/lowell.dennis/Code/loadtest/env/lib/python3.9/site-packages'] Server time: Sat, 24 Jul 2021 01:52:04 +0000 I am hoping that someone can see the error I am making. Here is my form class code code: class DynamicForm(Form): def __init__(self, *args, **kwargs): dynamic = kwargs.pop('dynamic', 0) super(DynamicForm, self).__init__(*args, **kwargs) for field in dynamic: self.fields[field[0]] = field[1] I am building an array of tuples, (name, field), where name is the name of the field and field is the field type (like CharField, ChoiceField, FloatField, IntegerField, URLField) with the prompt, initial, label, required and where needed choices items filled in). My view function ends with this: return render(request, 'loadtest.html', {'form': DynamicForm(dynamic = fields)}) My loadtest.html contains the following: <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table}} </table> <input type="submit" value="Submit"> </form> -
how do I configure my staticfiles in django?
I followed the procedures to setup staticfiles but I'm not getting what i want when I add an image to the section background it gives a wrong path "staticfiles/css/assets/img/oilcarriage.jpg" instead of "staticfiles/assets/img/oilcarriage.jpg" here's the path to the image: i would be really grateful if you can help me now :) -
how to add a mouse cropping feature to python project?
I am working on a project that allows users to upload their images and I wanted to be able to add a feature for them to crop it using the mouse, Can anyone please point out reliable resources or directions. so far I have to explore pillow, openCV. Also I am beginner developer and I keep running into machine learning sources to crop the image? is that a complicated task to accomplish, my python knowledge is mainly creating simple apps like to do lists, tic tac toe,... appreciate your help -
Heroku deployment of Django application with sqlite
I would like to deploy my Django application to Heroku. It is working perfectly in my localhost but when I tried to deploy, I get this error: ProgrammingError at / relation "myblog_category" does not exist LINE 1: ...g_category"."name", "myblog_category"."name" FROM "myblog_ca... The problem is probably related with my migrations but still can not solve. Is it related with sqlite? Thanks -
WAMP icon turns orange after adding mod_wsgi-express module-config results in httpd file
i am trying to deploy my django app on windows using wamp and mod_wsgi. the probleme is that the icone turns orange once i configure the httpd file and add the following lines resulting from the mod_wsgi-express module-config command : LoadFile "c:/users/zakaria/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/zakaria/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/users/zakaria/appdata/local/programs/python/python39" the error in the appache error log is stating : Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\wamp64\\bin\\apache\\apache2.4.46\\bin\\httpd.exe' sys.base_prefix = 'C:\\Users\\ZAKARIA\\AppData\\Local\\Programs\\Python\\Python39' sys.base_exec_prefix = 'C:\\Users\\ZAKARIA\\AppData\\Local\\Programs\\Python\\Python39' sys.platlibdir = 'lib' sys.executable = 'C:\\wamp64\\bin\\apache\\apache2.4.46\\bin\\httpd.exe' sys.prefix = 'C:\\Users\\ZAKARIA\\AppData\\Local\\Programs\\Python\\Python39' sys.exec_prefix = 'C:\\Users\\ZAKARIA\\AppData\\Local\\Programs\\Python\\Python39' sys.path = [ 'C:\\Users\\ZAKARIA\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', '.\\DLLs', '.\\lib', 'C:\\wamp64\\bin\\apache\\apache2.4.46\\bin', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Did you guys went trough a similar situation? Thanks in advance. -
Slugfield not working if field name is different from slug
Good evening, Django is completely new for me and it's my first question here. I'm trying to create a Webapp. I'm using Django, Python and MariaDB. I created a project with two apps and I have a model for each app. In the fist one I used "slug" as field name and everything is working fine. In the second one I wanted to differentiate that field giving a different name (bk_slug) defined as SlugField. I tried to use the same kind of instructions lines and modifying them for the filed name it seems not working. I cannot have the right URL (Class based ListView) and cannot acces to the DetailView.... Thanks in advance for your support. -
Why does React not seem to recognize Heroku's PORT env variable?
I am trying to deploy a frontend react application with a django backend. I am able to get Heroku's PORT environment variable just fine for the Django backend, but no matter what I do or try, process.env.PORT keeps returning undefined. I have tried adding a temporary variable that begins with REACT_APP that just reads the PORT variable in the procfile. Env files won't work because the PORT variable is dynamically allocated. Every resource I have found have said to either try a .env file or exporting the variable, but like I said, that is unrealistic because Heroku dynamically allocates the port. Any ideas? -
Add a skip parameter to Django CursorPagination
I'm looking to implement in Django 3(.1.7) something equivalent to the MongoDB cursor.skip() method. What I'm after is an additional query parameter to provide to my cursor-paginated REST endpoints in order to skip a given amount of items from the result of the query. I can't seem to find any example to obtain this result and I'd like not to reimplement the whole pagination class just to add this small addition. What's the right way to implement this? -
Event Listener for form submit is not working
What is the problem in the addEventListener method here? The code works until prepending the new_img, but when I am trying to make a form submit, the method is not even called. const reportForm = document.getElementById("report-form"); const img = document.getElementById("img"); reportBtn.addEventListener("click", () => { console.log("clicked"); new_img = document.createElement("img"); new_img.setAttribute("class", "w-100"); new_img.src = img.src; modalBody.prepend(new_img); reportForm.addEventListener("Submit", (e) => { e.preventDefault(); console.log("ajax method call"); const formData = new FormData(); formData.append("csrfmiddlewaretoken", csrf); formData.append("name", reportName.value); formData.append("remarks", reportRemarks.value); formData.append("image", new_img.src); $.ajax({ type: "POST", url: "reports/save/", data: formData, success: function (response) { console.log(response); }, error: function (error) { console.log(error); }, processData: false, contentType: false, }); }); }); The form is generated by django templates and placed inside the body of a modal like this: <input type="hidden" name="csrfmiddlewaretoken" value="FinPb8ZYsMj2RSHECGqKdMpLaLSofvs94LB5O7lcFOJpvLB4gUJn5ERaQz0a4DTz"> <div id="div_id_name" class="form-group"> <label for="id_name" class=" requiredField"> Name<span class="asteriskField">*</span> </label> <div class=""> <input type="text" name="name" maxlength="200" class="textinput textInput form-control" required id="id_name"> </div> </div> <div id="div_id_remarks" class="form-group"> <label for="id_remarks" class=" requiredField"> Remarks<span class="asteriskField">*</span> </label> <div class=""> <textarea name="remarks" cols="40" rows="10" class="textarea form-control" required id="id_remarks"></textarea> </div> </div> <br> <button type="button" class="btn btn-info">Save</button> -
How can i get unlimited SMS in django?
I want to send unlimited SMS to user in my django project. I currently using twilio service provider with limited number of SMS. -
Unable to create a user at django admin panel
Well, I'm not really sure that this problem is widespread. When I try to add a user from django's admin panel, I get the error about: The module in NAME could not be imported: django.contrib.main.password_validation.UserAttributeSimilarityValidator. Check your AUTH_PASSWORD_VALIDATORS setting From the body of the mistake I learned that: Exception Value: The module in NAME could not be imported: django.contrib.main.password_validation.UserAttributeSimilarityValidator. Check your AUTH_PASSWORD_VALIDATORS setting. Exception Location: C:\Users\Dmitriy\PycharmProjects\FileTime\venv\lib\site-packages\django\contrib\auth\password_validation.py, line 29, in get_password_validators The main problem is that there's nothing about 'get_password_validators' in that line (29) in that file (password_validation.py). The interesting thing is that I can create a user from command line. So, what can I do to solve this problem? -
query URL (query string) problem about "paginator" and "filter" in Django
my views.py: def subcategory(request, category_url): category = get_object_or_404(Category, category_url=category_url) subcategories = Subcategory.objects.filter(category=category) products_list = Product.objects.filter(product_category=category) subcatid = request.GET.getlist('subcategory') print(subcatid) if subcatid: ids = [int(id) for id in subcatid] subcategories1 = Subcategory.objects.filter(category=category, id__in=ids) products_list = Product.objects.filter(product_category=category, product_subcategory__in=subcategories1) else: subcategories1 = None products_list = Product.objects.filter(product_category=category) page = request.GET.get('page', 1) paginator = Paginator(products_list, 2) try: pass products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) if request.user.is_authenticated: wishlist = get_object_or_404(Wishlist, user=request.user.profile) else: wishlist = None ctx = {'products':products, 'products_list':products_list, 'wishlist':wishlist, 'subcategories':subcategories, 'category':category, 'subcategories1':subcategories1} return render(request, 'products/subcategory.html', ctx) my paginator html : <nav aria-label="Page navigation"> <ul class="pagination justify-content-center"> {% if products.number|add:'-4' > 1 %} <li class="page-item"> <a class="page-link" href="?page={{ products.number|add:'-5' }}" aria-label="Previous" tabindex="-1" aria-disabled="true"> <span aria-hidden="true"></span><< </a> </li> {% endif %} {% if products.has_previous %} <li class="page-item "> <a class="page-link page-link-prev" href="?page={{ products.previous_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" aria-label="Previous" tabindex="-1" aria-disabled="true"> <span aria-hidden="true"><i class="icon-long-arrow-right"></i></span>قبلی </a> </li> {% else %} <li class="page-item disabled"> <a class="page-link page-link-prev" href="" aria-label="Previous" tabindex="-1" aria-disabled="true"> <span aria-hidden="true"><i class="icon-long-arrow-right"></i></span>قبلی </a> </li> {% endif %} {% for i in products.paginator.page_range %} {% if products.number == i %} <li class="page-item active" aria-current="page"><a class="page-link" href="">{{ … -
how to effectively use UUID model field with django
If someone had to build a similar web application like Instagram using Django and expect a large user base as the start up grow, i am wondering if indexing the UUID model field while using postgres as a database would be a good idea after having modified the initial User model provided by django. class User(AbstractUser): id = models.UUIDField(primary_key=True, index=True, default=uuid.uuid4, editable=False) settings.py AUTH_USER_MODEL = "users.User" I have mentioned Instagram as an example to consider Read and Write of the database field in the application. I look forward to hear from anyone familiar with database and django good practices. Thank you -
Load a Django Form into Template using jQuery and stay on same page after submitting?
I am using Django function based views with a single template which contains multiple tabs. Depending on which tab is selected I hide/show certain elements on the page by catching .click() event using jQuery. I populate the visible elements using Ajax requests to certain view functions. I added a new tab to submit data via a form. Currently I have an additional template containing the form. When the tab is clicked, I load the template into an element using jQuery.load(upload.html). The form populates and posts to a Django view through a modelForm. It works alright however I can't seem to figure out how to stay on the same form tab after posting. Any redirect from Django causes the main template to reload to the default starting tab. Also, if the user navigates to main_template/upload.html the form is loaded outside of the main template page. I would like to avoid this. Am I going about this wrong ? main_template.html <div id="myForm"></div> $("#tabButton").click(function(){ $("#myForm").load("upload.html"); }); upload.html <form method="post" enctype="multipart/form-data" action="{% url 'core:upload' %}"> {% csrf_token %} {% bootstrap_form form layout='horizontal' %} {% bootstrap_button "Upload" button_type="submit" %} </form> urls.py urlpatterns = [ url('upload', views.upload, name='upload'), ] views.py def upload(request): if request.method == 'POST': … -
How can I avoid duplicate SQL queries with Django model forms?
I have the following models: from django.db import models class Author(models.Model): name = models.CharField(max_length=30) class Article(models.Models): author = models.ForeignKey(Author, on_delete=models.CASCADE) text = models.TextField() and a generic CreateView from django.views.generic.edit import CreateView urlpatterns += [ path("", CreateView.as_view(model=models.Article, fields="__all__")) ] with the following template (article_form.html) <form action="post"> {% csrf_token %} <table> {{ form }} </table> <input type="submit" value="Submit"> </form> I am using Django Debug Toolbar to list the performed SQL queries for each web request. My question is: Why is the following SQL query for the author list performed twice for each request? And how can I avoid the duplicate query? SELECT "myapp_author"."id", "myapp_author"."name" FROM "myapp_author" Moreover, the debug toolbar says that the first query took only 0.5 ms, whereas the second took 42 ms! Almost 100x longer. How can this be? I am using Django 3.2 with an SQLite database. Thank you! -
How to display N number of Movies the staffs has and the N number of Staffs the Movies has in Django Rest-framework api
I'm Creating a site where I Have models.py like below class Staff(models.Model): staff_name = models.CharField("Staff Name", max_length=25) staff_dob = models.DateField("Staff Date of Birth", help_text="Staff Born Date") staff_gender = models.IntegerField(choices=GENDER, help_text="Staff's Gender") staff_about = models.TextField("About the Staff") staff_pic = models.ImageField(upload_to="Anime/Staff/images/") class Movies(models.Model): author = models.CharField(help_text="Author name of the movie", max_length=50) country_of_origin = models.CharField("Country Of Origin", max_length=20) start_date = models.DateField("Start Date") end_date = models.DateField("End date") status = models.IntegerField(choices=RELEASE_STATUS, help_text="Current status of the movie") staffs = models.ForeignKey(Staff, on_delete=CASCADE) I want to display N number of Movies the Staffs have and N number of Staffs the Movie have. I'm new to Django and rest_framework. Thanks in advance. -
django RelatedObjectDoesNotExist error while creating
models: class FullNameMixin(models.Model): name_id = models.BigAutoField(primary_key = True, unique=False, default=None, blank=True) first_name = models.CharField(max_length=255, default=None, null=True) last_name = models.CharField(max_length=255, default=None, null=True) class Meta: abstract = True class Meta: db_table = 'fullname' class User(FullNameMixin): id = models.BigAutoField(primary_key = True) username = models.CharField(max_length=255, unique=True) email = models.CharField(max_length=255, unique=True) token = models.CharField(max_length=255, unique=True, null=True, blank=True) password = models.CharField(max_length=255) role = models.IntegerField(default=1) verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) def __str__(self): return self.username class Meta: db_table = 'cga_user' class Profile(FullNameMixin): id = models.BigAutoField(primary_key = True) birthday = models.DateTimeField(null=True, blank=True) country = models.CharField(max_length=255, null=True, blank=True) state = models.CharField(max_length=255, null=True, blank=True) postcode = models.CharField(max_length=255, null=True, blank=True) phone = models.CharField(max_length=255, null=True, blank=True) profession_headline = models.CharField(max_length=255, null=True, blank=True) image = models.ImageField(upload_to=get_upload_path, null=True, blank=True) profile_banner = models.ImageField(upload_to=get_upload_path_banner, null=True, blank=True) cga_user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE, related_name="profile") gender = models.CharField( max_length=255, blank=True, default="", choices=USER_GENDER_CHOICES ) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) class Meta: db_table = 'profile' When i am creating Profile from django admin panel getting below error. e filename = self.upload_to(instance, filename) File "/Users/soubhagyapradhan/Desktop/upwork/africa/backend/api/model_utils/utils.py", line 7, in get_upload_path instance.user, File "/Users/soubhagyapradhan/Desktop/upwork/africa/backend/env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 421, in __get__ raise self.RelatedObjectDoesNotExist( api.models.FullNameMixin.user.RelatedObjectDoesNotExist: Profile has no user. [24/Jul/2021 13:49:51] "POST /admin/api/profile/add/ HTTP/1.1" 500 199997 … -
therw is an error of circular import how to resolve the error?
Django.core.exceptions.ImproperlyConfigured: The included URLconf 'travelproject1.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
How to display questions based on subcategory using Django Rest Framework?
I want to display all questions based on subcategory. This is my code : models.py class Subcategory(models.Model): subcategory_id = models.BigAutoField(primary_key=True) subcategory = models.CharField(max_length=40) class Meta: managed = True db_table = 'subcategory' def __str__(self): return self.subcategory class Question(models.Model): question_id = models.BigAutoField(primary_key=True) subcategory = models.ForeignKey('Subcategory', models.DO_NOTHING, default=None) question = models.TextField() answer = models.CharField(max_length=255) class Meta: managed = True db_table = 'question' def __str__(self): return self.question serializers.py class SubcategorySerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('subcategory_id', 'subcategory') class QuestionSerializer(serializers.ModelSerializer): subcategory = serializers.StringRelatedField() class Meta: model = Question fields = ('question_id', 'subcategory', 'question', 'answer') view.py @api_view(['GET', 'POST', 'DELETE']) def question_list(request): # GET list of question, POST a new question, DELETE all question if request.method == 'GET': questions = Question.objects.all() question = request.GET.get('question', None) if question is not None: questions = questions.filter(question__icontains=question) questions_serializer = QuestionSerializer(questions, many=True) return JsonResponse(questions_serializer.data, safe=False) # 'safe=False' for objects serialization elif request.method == 'POST': question_data = JSONParser().parse(request) questions_serializer = QuestionSerializer(data=question_data) if questions_serializer.is_valid(): questions_serializer.save() return JsonResponse(questions_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(questions_serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': count = Question.objects.all().delete() return JsonResponse({'message': '{} Questions were deleted successfully!'.format(count[0])}, status=status.HTTP_204_NO_CONTENT) /api/subcategory : [ { subcategory_id: 1, subcategory: "Mathematics" }, { subcategory_id: 2, subcategory: "History" } ] /api/questions : [ { question_id: 1, subcategory: 1, question: "10 … -
Django data in tables not showing up
My tables in my django don't show up , the titles for the table do but the data itself does not. can someone tell me what is wrong with my code dashboard.html {% extends 'accounts/main.html' %} {% block content %} {% include 'accounts/status.html' %} <div class="col-md-16"> <h5>LAST 5 ORDERS</h5> <hr> <div class="card card-body"> <a class="btn btn-primary btn-sm btn-block" href="">Create Order</a> <table class="table table-sm"> <tr> <th>Title</th> <th>Language</th> <th>Rating</th> <th>Type of Media</th> <th>Genre</th> <th>Review</th> <th>Notes</th> <th>Date</th> <th>Update</th> <th>Remove</th> </tr> {% for media in mediass %} <tr> <td>{{media.title}}</td> <td>{{media.language}}</td> <td>{{media.rating}}</td> <td>{{media.type_of_media}}</td> <td>{{media.genre}}</td> <td>{{media.review}}</td> <td>{{media.notes}}</td> <td>{{media.date}}</td> <td><a href="">Update</a></td> <td><a href="">Delete</a></td> </tr> {% endfor %} </table> </div> </div> {% endblock %} models.py from django.db import models class Media(models.Model): CATEGORY = ( ('Movie', 'Movie'), ('Tv Show', 'Tv Show'), ('Drama', 'Drama'), ('Other', 'Other'), ) NUMBER = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ) GROUP = ( ('Action', 'Action'), ('Anime', 'Anime'), ('Comedy', 'Comedy'), ('Crime', 'Crime'), ('Fantasy', 'Fantasy'), ('Horror', 'Horror'), ('Romance', 'Romance'), ('Other', 'Other'), ) title = models.CharField(max_length=200, null=True) language = models.CharField(max_length=200, null=True) rating = models.CharField(max_length=200, null=True, choices=NUMBER) type_of_media = models.CharField(max_length=200, null=True, choices=CATEGORY) genre = models.CharField(max_length=200, null=True, choices=GROUP) review = models.CharField(max_length=1000, null=True) notes = models.CharField(max_length=1000, null=True, blank=True) date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return … -
Django not finding The Project module:
Everyone This is my first Django project for university, our project name is Hotel and every time I run: python manage.py runserver I get : ModuleNotFoundError: No module named 'Hotel' The traceback is: Traceback (most recent call last): File "C:\python3\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\python3\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\python3\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\python3\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\python3\lib\site-packages\django\conf\__init__.py", line 82, in getattr self._setup(name) File "C:\python3\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\python3\lib\site-packages\django\conf\__init__.py", line 170, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\python3\lib\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 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'Hotel' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\LENOVO\Desktop\Hotel\manage.py", line 22, in <module> main() File "C:\Users\LENOVO\Desktop\Hotel\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\python3\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() …