Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django GET returning only 1 child instead of collection
I'm having an issue getting a list of objects with a GET request on this endpoint: /api/stock/{bar_id}/ It should return a list of stock for a specific Bar ID. In my schema, the Stock model contains the following properties: bar_id as a foreign key. ref_id as a foreign key. stock as integer. sold as integer. When I make the GET request I only end up getting the first stock, but I should be getting the full list of stocks. I understand that this end point is not RESTful, however it is an imposed constraint I have to make do with it and can't even pass the bar_id as parameter. What am I missing or doing wrong? Thanks for your responses! Object returned after the GET request: { "ref_id": { "ref": "first", "name": "first one", "description": "description" }, "bar_id": 1, "stock": 10, "sold": 0 } Expected returned object after the GET request: { [ { "ref_id": { "ref": "first", "name": "first one", "description": "description" }, "bar_id": 1, "stock": 10, "sold": 0 }, { "ref_id": { "ref": "second", "name": "second one", "description": "description" }, "bar_id": 1, "stock": 10, "sold": 0 } ] } Here is my BarSerializer: from rest_framework import serializers from … -
AttributeError: 'QuerySet' object has no attribute 'objects' when using count
I have a problem with show total number of my list. I want to count the total number of my list_value variable below, but it seems it returning an error. AttributeError: 'QuerySet' object has no attribute 'objects' when using count views.py @login_required(login_url='log_permission') def data_table(request): if request.method=='POST': province = request.POST['province'] municipality = request.POST['municipality'] list_value = Person.objects.filter(province=province,municipality=municipality) final_value = list_value.objects.count() //here is the problem print(final_value) return render(request, 'data_table.html') models class Person(models.Model): covid_id = models.CharField(max_length=50) firstname = models.CharField(max_length=50) middle = models.CharField(max_length=50,blank=True, null=True) lastname = models.CharField(max_length=50,blank=True) extension = models.CharField(max_length=50,blank=True, null=True) province = models.CharField(max_length=50) municipality = models.CharField(max_length=50) barangay = models.CharField(max_length=50) remarks = models.CharField(max_length=50) amount = models.CharField(max_length=50) remarks_miray = models.CharField(max_length=50) count = models.CharField(max_length=50) -
TypeError: missing 2 required positional arguments
from django.db import models from hospital.models import HospitalList from django.db.models.signals import post_save from django.dispatch import receiver class DoctorList(models.Model): doctorname = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HospitalList, related_name="h_code", on_delete=models.CASCADE) @receiver(post_save) def set_h_code(instance, created, **kwargs): testhospital = HospitalList.objects.get(code = h_code).values('code') instance.d_code = testhospital instance.save() d_code = models.CharField(primary_key=True, max_length = 200, default=set_h_code, editable=False) error code: TypeError: set_h_code() missing 2 required positional arguments: 'instance' and 'created' I don't know why the error occurs. What is the problem? Thanks in advance to those who respond. -
Invalid HTTP_HOST header: 'api.binance.com'
I keep on getting this error the moment I enabled error messaging in Django. I research about it. This binance thingy is about bitcoin and it is not related to what I'm doing. Is this an attack that's trying to check/access my Django Web app? Invalid HTTP_HOST header: 'api.binance.com'. You may need to add 'api.binance.com' to ALLOWED_HOSTS. Report at /api/v1/time Invalid HTTP_HOST header: 'api.binance.com'. You may need to add 'api.binance.com' to ALLOWED_HOSTS. Request Method: GET I check the api.binance.com. It is like an api and it says "ok" What's your thought about this? -
Django submit button refreshes page and does not remove values
I'm trying to get this submit button to work in my CreateView and have been debugging for quite some time now. Basically when I enter my values into the form and click submit, the page refreshes and all the values simply remain there. I do have a form_valid method where I print form.cleaned_data, but over at the terminal, it only shows a POST request but did not show form.cleaned_data. I'm really not sure where the problem is at all. I've tried setting action="." in my html but it simply says page not found. Any help is super appreciated! Template: travelandentertainment_create.html: {% extends "user/base.html" %} {% load crispy_forms_tags %} {% load static %} {% load widget_tweaks %} {% block topbar %} {% if user.is_authenticated %} <a class="navbar-brand" href="{% url 'budget-home' %}">Select Category</a> <a class="navbar-brand" href="{% url 'logout' %}">Logout</a> {% else %} <a class="navbar-brand" href="{% url 'register' %}">Register</a> {% endif %} {% endblock %} {% block content %} <a class="btn btn-success mb-3 mt-3" href="{% url 'budget-home' %}" role="button">Back</a> <a class="btn btn-success mb-3 mt-3" href="{% url 'budget-travelandentertainment_list' %}" role="button">View Submitted List</a> <form method="POST"> {% csrf_token %} <div class="field"> <label class="label">Company</label> <div class="control"> {% render_field form.company class="form-control" %} </div> </div> <div class="field"> <label class="label">Air … -
Does using static variables in django views a good practise?
Assuming the get method is called at least one time before the post method.(This is not my actual code, if there's any silly mistake, don't consider it, my question is CAN I INSTANTIATE AND USE STATIC VARIABLE LIKE BELOW) class McqView(View): course=None all_questions=None start_time=None def get(self,request,someid): if not McqView.course: McqView.course = Course.objects.get(id=someid) if not McqView.all_questions: McqView.all_questions = Question.objects.filter(course=McqExamView.course) if not McqView.start_time: McqView.start_time = datetime.now() #using the static variables somewhere here def post(self,request): #using the same static variables somewhere here I thought of using the two as member variables but it is not possible. So I thought of using the two as static variables. will any problem arise while using this method? like 1.The static variables become None 2.The static variables gets instantiated more than once. If the second case happens, the start_time variable value will become wrong. Please tell me whether this is a wrong approach, if it is wrong tell me an alternative way of doing the same. -
How to make the ImageField optional in django rest framework API
I'm pretty tired finding solution to make the imagefield optional in django rest framework API. I tried each and every solution I found in stack overflow but nothing seems to be working fine. I know there are fewer posts related to same query but I didn't find the solution in that. Let me explain you what is my requirements. Here is my User model with some basic info fields including an Image field. models.py class User(models.Model): firstname = models.CharField(max_length=100, validators=[firstname_check]) lastname = models.CharField(max_length=100, blank=True, null=True, validators=[lastname_check]) username = models.CharField(max_length=100, unique=True, blank=True, null=True, validators=[username_check]) email = models.EmailField(max_length=100, unique=True) password = models.CharField(max_length=50, blank=True, null=True, validators=[password_check]) mobnum = models.CharField(max_length=50, blank=True, null=True, validators=[mobile_num_len]) timestamp = models.DateTimeField(auto_now=True) gender = models.CharField(max_length=50, blank=True, null=True) language = models.CharField(max_length=100, blank=True, null=True) profile_img = models.ImageField(upload_to ='uploads/', blank=True, null=True) is_active = models.BooleanField(default=False, blank=True, null=True) serializer.py from utils import Base64ImageField class UserMannualSerializer(serializers.ModelSerializer): profile_img = Base64ImageField( max_length=None, use_url=True, allow_empty_file=True, required=False ) class Meta: model = User fields = [ 'firstname', 'lastname', 'username', 'email', 'password', 'mobnum', 'gender', 'language', 'timestamp' 'profile_img' ] Here is the Base64ImageField() function which I've written inside the utils.py file. Which will take the base64 string and convert it back and store in the server and that is happening properly. But … -
Django problem: RuntimeError: __class__ not set defining 'AbstractBaseUser' as
Just upgraded Ubuntu from 18.04 to 20.04 and my Django project failed (it worked fine on Ubuntu 18.04) with the following message: Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x7fc139bd14c0> Traceback (most recent call last): File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/yltang/webapps/virtualenv/yltantVenv/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was __classcell__ propagated to type.__new__? My requirements.txt is as follows: appdirs==1.4.2 beautifulsoup4==4.5.3 certifi==2018.4.16 chardet==3.0.4 dj-database-url==0.4.2 dj-static==0.0.6 Django==1.10.6 django-toolbelt==0.0.1 gunicorn==19.7.0 idna==2.6 packaging==16.8 psycopg2==2.8.6 … -
Foreign key multiple images not saving in django
i am trying to save a form with multiple images. I have two models post model and images model. The problem is when i try to upload the post the images are not saving. i can upload images in form but when i click Post it only save title, images are not save. Can someone point me what i do wrong please? Models.py class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) class Images(models.Model): article = models.ForeignKey(POst, default=None, on_delete=models.CASCADE) images = models.ImageField(upload_to='media/images/',blank=True, null=True) Views.py class CreatePost(CreateView): model = Post form_class = Createpost template_name = 'add_post.html' def get_context_data(self, **kwargs): data = super(CreatePost, self).get_context_data(**kwargs) data['form_images'] = PostImageFormSet() if self.request.POST: data['form_images'] = PostImageFormSet(self.request.POST, self.request.FILES) else: data['form_images'] = PostImageFormSet() return data def form_valid(self, form): form.instance.author = self.request.user context = self.get_context_data() form_img = context['form_images'] atc = form.save(commit=False) save = atc.save() if form_img.is_valid(): form_img.instance = save form_img.save() form.save_m2m() return super(CreatePost, self).form_valid(form) def get_success_url(self): return reverse('detail', args=(self.object.id,)) forms.py class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Images exclude = () widgets = { 'images': forms.ClearableFileInput(attrs={'multiple':True}), } class CreatePost(forms.ModelForm): class Meta: model = Post fields = ["title",] PostImageFormSet = inlineformset_factory( Post, Images, form=ImageForm, extra=1, can_delete=True, #fields=['images'], ) templates <form class="post" method="POST" enctype="multipart/form-data" > {% csrf_token %} {{form.title.label_tag … -
Pagination for Django with big data
I tried to install pagination into Django app. I searched many codes online how to do that but most of them are for pagination with small amount of data. My app has close to 1 million PostgreSQL data. It seems like handling those big data with a typical pagination system does not work. you can see tons of pagination there. I want to line them like << 1 2 3 4 5 6 7 8 9 10 >> Here are my codes. urls.py urlpatterns = [ path('', views.find,name='find'), path('<int:num>', views.find, name='find'), path('detail/<str:pk>', DbDetail.as_view()), path('list', views.DbList.as_view(), name='list'), ] views.py class DbList(ListView): model = TestEu paginate_by = 10 def get_queryset(self): q_word = self.request.GET.get('query') if q_word: sql = 'select * from test_eu' sql += " where eng_discription ~ '.*" + q_word +".*'" object_list = TestEu.objects.raw(sql) else: sql = 'select * from test_eu' msg = "abcdefg" sql += " where eng_discription ~ '.*" + msg +".*' ORDER BY image_amount DESC " object_list = TestEu.objects.raw(sql) # object_list = TestEu.objects.all() return object_list testeu_list.html {% if is_paginated %} <nav aria-label="Page navigation"> <ul class="pagination justify-content-center"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% endif %} {% for … -
How to convert the list into a list of dictionaries?
I have a list like this. ls = ['Size:10,color:red,', 'Size:10,color: blue,'] I want to convert the list into this format. [{'Size':'10','color':'red'}, {'Size':'10','color': 'blue'}] What I have tried is: [dict([pair.split(":", 1)]) for pair in ls] # It gave me output like this. [{'Size': '10,color:red,'}, {'Size': '10,color: blue,'}] But this method works if the list is like this ['color:blue,'] but didn't worked properly with the above list. -
allowedhosts=[] using Django and Apache2
I have a Django project and I am using Apache2. My settings.py file looks like this: DEBUG = False ALLOWED_HOSTS = ['localhost', '165.232.125.35', '.meesuis.org', 'www.meesuis.org'] When I type the 165.232.125.35 the site comes up fine. But when I type the actual website name it doesn't work. Can someone please confirm that I have the settings.py file set up correctly so that I will know for sure the problem is somewhere else? Thank you. -
Reverse for 'update_task' with arguments '('',)' not found. 1 pattern(s) tried: ['update/(?P<update>[^/]+)/$']
I am building a small CRUD project and stuck on a very basic thing which is an update. First I found it on stack overflow, google and Facebook as well but couldn't be able to find the solution so finally posting my problem here will all code. views.py: from django.shortcuts import render, redirect, get_object_or_404, HttpResponseRedirect from .models import Task from .forms import TaskForm def tasks(request): task = Task.objects.all() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = TaskForm() context = { 'forms': form, 'tasks': task } return render(request, 'task/task.html', context) def update_task(request, update): task = Task.objects.get(id=update) form = TaskForm(instance=task) if request.method == 'POST': form = TaskForm(request.POST, instance=task) if form.is_valid(): form.save() return redirect('/') context = { 'form': form } return render(request, 'task/update_task.html', context) urls.py: from django.urls import path from .views import tasks, update_task urlpatterns = [ path('', tasks, name='tasks'), path('update/<str:update>/', update_task, name='update_task'), ] I am facing a problem in this section of update_task.html. my update_task.html: <form action="{% url 'update_task' form.id %}" method="POST"> {% csrf_token %} {{ form }} </form> <input type="submit" value="Update"> tasks.html: <!DOCTYPE HTML> {% load static %} {% load crispy_forms_tags %} <html lang="en"> <head> <meta charset="UTF-8"> <title>ToDo App</title> <link rel="stylesheet" href="{% static 'css/mystyles.css' … -
Django projects fail on Ubuntu 20.04
I just upgraded Ubuntu from 18.04 to 20.04, and ALL my Django projects (tens of them) were not working. One of the problem related to psycopg2 when executing pip: For example, there is "psycopg2==2.7.3.1" in my "requirements.txt" file, and running "pip install -r requirements.txt" resulted in errors when building wheel for psycopg2. Change "psycopg2==2.7.3.1" to ""psycopg2-binary" solved the problem. So, is such change necessary for all projects running on Ubuntu 20.04? Other error examples from various projects when running server: RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was __classcell__ propagated to type.__new__? SyntaxError: Generator expression must be parenthesized (widgets.py, line 151) AssertionError: SRE module mismatch ModuleNotFoundError: No module named 'decimal' ... etc. How to I fix these problems? I've been in a headache for weeks. -
How to customize response message in ModelViewSet
I will send the request in post format using ModelViewSet and I will customize its response message. So I turned the response back on the perform_create method as shown in the following code, but it doesn't work as I want. class CreateReadPostView (ModelViewSet) : serializer_class = PostSerializer permission_classes = [IsAuthenticated] queryset = Post.objects.all() pagination_class = LargeResultsSetPagination def perform_create (self, serializer) : serializer.save(author=self.request.user) return Response({'success': '게시물이 저장 되었습니다.'}, status=201) # it's not work How can I make this work normally? Thank in advance. -
Is there easier way to use bulk_create() with many query to instance create items
I don't have basic programming at all and just learned python and Django a few months ago, due to an urgent need I decided to create my own program to support my department and team After the program is running, I want to make it easier for the user and after I look around it is recommended to use bulk_create and ajax JavaScript, definitely not using JavaScript. After looking for ways to use bulk_create, I find it inefficient like: instance = get_object_or_404(Audit, id=766) item1 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=1) item2 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=2) item3 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=3) item4 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=4) item5 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=5) item6 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=6) item7 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=7) item8 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=8) item9 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=9) item10 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=10) item11 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=11) item12 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=12) audit_mie = [ AuditItem(audit=instance,item=item1,kategori=item1.kategori.kategori), AuditItem(audit=instance,item=item2,kategori=item2.kategori.kategori), AuditItem(audit=instance,item=item3,kategori=item3.kategori.kategori), AuditItem(audit=instance,item=item4,kategori=item4.kategori.kategori), AuditItem(audit=instance,item=item5,kategori=item5.kategori.kategori), AuditItem(audit=instance,item=item6,kategori=item6.kategori.kategori), AuditItem(audit=instance,item=item7,kategori=item7.kategori.kategori), AuditItem(audit=instance,item=item8,kategori=item8.kategori.kategori), AuditItem(audit=instance,item=item9,kategori=item9.kategori.kategori), AuditItem(audit=instance,item=item10,kategori=item10.kategori.kategori), AuditItem(audit=instance,item=item11,kategori=item11.kategori.kategori), AuditItem(audit=instance,item=item12,kategori=item12.kategori.kategori), ] AuditItem.objects.bulk_create(audit_mie) is there an easier way besides the method above? if not, then I stick with it, by creating objects in each item id which is approximately 130 (currently) and I will group it into 8 (currently) bulk_create() method. I am stuck here, if anyone can help this to make it easier, I am very, very Thank you -
Recommendations for possible feed algorithms?
I am currently tasked with creating an algorithm that delivers a continuous flow of posts to the end user via an endless scrolling mechanism. There are some obvious answers (e.i. display posts via date created and show them chronologically). However, this has some major drawbacks (e.i. depending on the timezone, some posts will get burried while others get all the attention arbitrarily). What are some alternative ways (with coding examples) to implement an algorithmic feed? Any resources/blog posts would be greatly appreciated. -
ModelAdmin - how to inline model to another model view using intermediate relation table using foreign key
I want to make able to edit (add or delete) film work persons (actors, writers, director). I have the following models: class FilmWork(models.Model): id = models.UUIDField(primary_key=True, db_column='id', default=uuid.uuid4) title = models.CharField(_('название'), max_length=255) class Meta: db_table = 'film_work' managed = False class Person(models.Model): id = models.UUIDField(primary_key=True, db_column='id', default=uuid.uuid4) full_name = models.TextField(_('полное имя'), max_length=255) class Meta: db_table = 'person' managed = False class FilmWorkPerson(models.Model): id = models.UUIDField(primary_key=True, db_column='id', default=uuid.uuid4) film_work = models.ForeignKey(FilmWork, models.DO_NOTHING, blank=True, null=True, related_name='film_work_person') person = models.ForeignKey(Person, models.DO_NOTHING, blank=True, null=True, related_name='person') role = models.CharField(_('роль'), max_length=50, choices=PersonRole.choices) class Meta: db_table = 'film_work_person' unique_together = (('film_work', 'person', 'role'),) managed = False Now I don't know how to show 'full_name' and 'role' fields on the FilmWorkAdmin(admin.ModelAdmin) - I found that Inline could help, but since I have intermediate table FilmWorkPerson which has ForeignKey field pointing to FilmWork, I can display 'role', but 'full_name' seems unaccessible in any way. Since it is not ManyToMany but ForeignKey I can not use 'through' I can't use fields lookup like 'person__full_name' since it is available in QuerySets filters only(?) I can not directly inline Person from FilmWorkAdmin since there are no direct connection between FilmWork and Person (did I miss some reverse lookup tool?) I don't believe … -
Tensorflow - ImportError: DLL load failed while importing _pywrap_tensorflow_internal
I have built a website using django and whenever I try to run my manage.py, I get the below error. I don't know what's wrong there and what am I missing Traceback (most recent call last): File "C:\venvs\mazroo3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 64, in <module> from tensorflow.python._pywrap_tensorflow_internal import * ImportError: DLL load failed while importing _pywrap_tensorflow_internal: A dynamic link library (DLL) initialization routine failed. During handling of the above exception, another exception occurred: 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 "C:\venvs\mazroo3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\venvs\mazroo3\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\venvs\mazroo3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\venvs\mazroo3\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\venvs\mazroo3\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\khubi\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\khubi\sizeit\products\models.py", line 8, in <module> from predictionAPI.main import mlAPIforProduct File "C:\Users\khubi\sizeit\predictionAPI\main.py", line 3, in <module> import tensorflow as tf File "C:\venvs\mazroo3\lib\site-packages\tensorflow\__init__.py", … -
Exception in thread django-main-thread - error
I ran the server but somehow there happened to be a lot of errors - I can't understand the errors plz help I changed the design and started to use templates - html & css changed url to go to html file error code : Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 399, in check for pattern in self.url_patterns: File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 584, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 577, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) . . . url(r'^', include('main.urls')), #localhost:8000으로 요청이 들어오면 main.urls로 전달 NameError: name 'url' is not … -
How can I serve a stand-alone static app through Django
We're using django for authentication, user management, site content etc, but we have a JS tool that needs to be behind django auth as well. The tool is an html page that pulls in a couple dozen static files through relative paths in the html page (src="./someJSfile.js"). The problem is I can't figure out how to serve the html file through django but keep the relative paths intact. I can create an apache alias to that directory so that the relative paths are intact, but then the html is served through apache and bypasses auth. I would like to be able to have the html file served through a django view so that auth works, and also keep the static files in the same directory. Is there some apache magic where I can have the html served through django but have the static served through apache using an alias, while keeping the html and static in the same directory? Thanks in advance -
django, typeerror: missing 1 required positional argument
models.py: class DoctorList(models.Model): doctorname = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HospitalList, related_name="h_code", on_delete=models.CASCADE) def doctor_code_create(DoctorList): last_doctor_code = DoctorList.objects.all().order_by('d_code').last() testhospital = DoctorList.objects.filter().values('h_code') if not last_doctor_code: return 'd' + '001' d_code = last_doctor_code.d_code doctor_int = int(d_code[3:7]) new_doctor_int = doctor_int + 1 new_d_code = 'd' + str(testhospital) + str(new_doctor_int).zfill(3) return new_d_code d_code = models.CharField(primary_key=True, max_length = 200, default = doctor_code_create, editable=False) error code: Got a `TypeError` when calling `DoctorList.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `DoctorList.objects.create()`. You may need to make the field read-only, or override the DoctorListSerializer.create() method to handle this correctly. Original exception was: Traceback (most recent call last): File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\rest_framework\serializers.py", line 948, in create instance = ModelClass._default_manager.create(**validated_data) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\query.py", line 445, in create obj = self.model(**kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\base.py", line 475, in __init__ val = field.get_default() File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\fields\__init__.py", line 831, in get_default return self._get_default() TypeError: doctor_code_create() missing 1 required positional argument: 'DoctorList' I want to use h_code that exists in class DoctorList (models.Model) by putting it in doctor_code_create. I think it's right to use it like this, but I don't know what went wrong. Do I … -
Persistent "[Errno 61] Connection refused" error in Django
in my Django project, I am running these commands on shell: >>> from django.core.mail import send_mail >>> send_mail('Django mail', 'This e-mail was sent with Django.', 'my@email.com' ['out@email.com'], fail_silently=False) I keep receiving this error: ConnectionRefusedError: [Errno 61] Connection refused This is my current settings.py: import os import smtpd from pathlib import Path ... EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'my@email.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True The strange thing is that I still receive the same error even when I add this code to write emails to console instead: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' I have tried all the tips I could find including, activating less secure apps in Gmail, acquiring a Gmail app password, and even tried using Mailjet with django-anymail. Nothing made a difference, still received the same error message when I run that command in shell. I'm running Python 3.6 and Django 3.1.2 -
Deploy Web Application Nuxtjs/Django/PostgreSQL
Right now I'm developing a website base on Nuxt as the Frontend and Django as the backend with a PostgreSQL database, I'm a little new to this field but I'm not sure how exactly to deploy and host my app, I've been looking at AWS Services to do it, like using Lightsail or just deploy everything on an ES2 instance to save money instead of deploying each element on a different server, the problem with the last option is that it wont be able to scale, in case in the future the visits to the site increase. I really appreciate some recommendation or orientation about how I could do it this easy, cheap and scalable. -
How to pass multi optional URL parameters in django?
How to pass multi optional URL parameters? For example I want pass 2 params: my_color and my_year, but they are optional, so may be none of them will be passed, may be both, or may be only one. Currently in urls.py I have : urlpatterns = [ re_path(r'^products/(?P<my_color>.*)/(?P<my_year>.*)$', some_view), ] This obviously is not correct and works only if both of them are passed. What would be correct solution? P.S. I found answers when only one optional parameter needs to be pass, but not figured out how to do same for few parameters. Also it seems "multiple-routes option" is not solution in this case ?