Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django error "no module named ..." after manage.py runserver. Did I organize my files correctly?
I'm new to Python and Django. I'm trying to create a user authentication system with Djoser following an online tutorial. I am getting this error "no module named "auth_system"" when I try to run the server to test the connection with Postman. Is it because of the way that I organized the folders that my "auth_system" file is not recognized? Also, is the way that I put all the files into the virtual environment folder correct? -
Django "type object X has no attribute POST"
For some reason, I cannot do this without result in an error. How does TodoForm have no attribute to POST? All the other example shows it's valid. from django.shortcuts import render from .models import Todo from .forms import TodoForm def index(request): return render(request, 'home.html') def todoPanel(request): if request.method == 'POST': form = TodoForm.POST(request.POST) if form.is_valid(): print('steve') else: form = TodoForm() return render(request, 'todo_panel.html', {'form': form}) -
django-q and azure app service. Unable to start backend process in azure app service
I am using django application for my web based application, now to implement async functionality I am using django q package. Using this I have put some functionality behind the user interface and it is working locally. But once code is deployed into the azure app service (Linux plan) it is not working. It is not working because as part of Django-q we have to run the cluster in the backend. It looks like this python manage.py qcluster As I am not able to start the background process in-app service this specific functionality is not working. I have tried to add the custom startup command in app service but nothing is working out. Tried creating a custom shell script and placed it in the /home directory but that is also not working and tried calling the script from startup command but not working. Note :- The application is being deployed to app service via azure devops pipelines. Thanks for your help. -
Error when running collecstatic with Django
I am getting an extremely frustrating error when I run collectstatic on a django project I have. Here is the error: django.core.exceptions.SuspiciousFileOperation: The joined path (/home/carhea/dev-server/CAM-Freiburg/font/roboto/Roboto-Thin.eot) is located outside of the base path component (/home/carhea/dev-server/CAM-Freiburg/staticfiles) I am running this on a Ubuntu 20.4 server using Django 2.2 and python v.3.7 My static settings in settings.py are quite standard... This only recently happened! STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage ' Any help would be greatly appreciated! I also assume that I didn't give enough information :P -
Timer setup with django
I want to create an app for exam room types. I don't know how to set up the timer. An admin can start the timer. but I want to know how I can implement a function where everyone will see the timer going on. like the exam starts at 10 am, so if anyone enters the room at 10.20 am he will see 20 has passed already. can anyone help me with it? any suggestion is appreciable. -
How do I download xlsx file with Django?
I try to make a button for downloading a xlsx file using django. I followed this tutorial https://xlsxwriter.readthedocs.io/example_django_simple.html I have an HTTP response but no download prompt is showing. There is some parts of my code : views.py: def xlsx(request): if request.method == "POST": output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet("hello") worksheet.write(0,0, 'Client') workbook.close() output.seek(0) filename = 'EdedocBilling.xlsx' response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename) return response index.html <form>...</form> <button type = "button" id = "saveID" onclick = "$.ajax({ type: 'POST', url: 'xlsx', async: false, data: $('form').serialize(), success : console.log(' Success') })"> Generate </button> I remove the part were I process the data since the xlsx file generated works fine (I tested creating the file on the server and it worked). Here is the HTTP response headers: HTTP/1.1 200 OK Date: Thu, 08 Jul 2021 14:47:37 GMT Server: WSGIServer/0.2 CPython/3.8.8 Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet Content-Disposition: attachment; filename="EdedocBilling.xlsx" X-Frame-Options: DENY Content-Length: 5252 X-Content-Type-Options: nosniff Referrer-Policy: same-origin Does somebody has a solution? Thanks ! -
two models issue in django tryung to connect them
i create two model name subject and section if i create a model name maths i want to create some section in it which is one to one so i am trying to load the page of a section acc to the subject like i click on maths link only the section which is relate to math open no other section open i think you understand so here is my code my models.py class Subject(models.Model): name = models.CharField(max_length=80, blank=False,) thumbnail = models.ImageField(upload_to='subject thumbnail', blank = False) total_Section = models.FloatField(default='0') joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Section(models.Model): subject = models.OneToOneField(Subject, on_delete=models.CASCADE) sub_section = models.CharField(max_length=500, blank=True) title = models.CharField(max_length=5000, blank=False) teacher = models.CharField(max_length=500, blank=False) file = models.FileField(upload_to='section_vedios', blank=False) price = models.FloatField(blank=False) content_duration = models.DurationField(blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title my views.py for subject @login_required def home(request): subject_list = Subject.objects.all() return render (request, 'home.html', {'subject_list': subject_list }) my views.py for sections @login_required def sections(request): return render (request, 'sections.html',) my html for subject it worked <ul> {% for subject in subject_list %} <li class="sub"> <a name='thumb' class="thumb" href="{% url 'subjects:section' %}"><img class="thumbnail" src="{{ subject.thumbnail.url }}" alt=""> <span><strong> {{ subject.name }} </strong> </span> </a> <p>No … -
Django the view app_view.views.GetHtmlView didn't return an HttpResponse object. It returned None instead
A production view throws a "The view app_view.views.GetHtmlView didn't return an HttpResponse object. It returned None instead." error every time, i.e. sometimes it returns an answer, and sometimes it returns an error. But the same view works without errors on the test server. What could be the problem? This my view class GetHtmlView(View): def get(self, request): html_name = request.GET.get('htmlName') html = render_to_string(f'front_view/{html_name}') # ... some code if request.is_ajax(): return JsonResponse({'html': html}) preprare_html = # ... some code return JsonResponse({'html': preprare_html}) -
get() returned more than one Member -- it returned 11
I am a student studying Django. I am implementing so that member information can be edited on My Page. But I faced the following error: I want all members to be able to edit their information on My Page. I want to be able to get the name, username, and phone information in the Model table respectively. I know that the get() part in views.py is the problem, but it seems crazy because of the solution. How can I solve this? Any help would be appreciated. Error Detail : MultipleObjectsReturned at /mypage/mypage_modify/ get() returned more than one Member -- it returned 11! Request Method: POST Request URL: http://127.0.0.1:8000/mypage/mypage_modify/ Django Version: 3.1.5 Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one Member -- it returned 11! Exception Location: D:\anaconda3\envs\vnv_zn\lib\site-packages\django\db\models\query.py, line 436, in get Python Executable: D:\anaconda3\envs\vnv_zn\python.exe Python Version: 3.7.6 Python Path: ['C:\\zeronine_project', 'D:\\anaconda3\\envs\\vnv_zn\\python37.zip', 'D:\\anaconda3\\envs\\vnv_zn\\DLLs', 'D:\\anaconda3\\envs\\vnv_zn\\lib', 'D:\\anaconda3\\envs\\vnv_zn', 'D:\\anaconda3\\envs\\vnv_zn\\lib\\site-packages'] Server time: Thu, 08 Jul 2021 23:33:38 +0900 View.py from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from mypage.forms import * from zeronine.models import * # Create your views here. def mypage_list(request): categories = Category.objects.all() return render(request, 'mypage/mypage_list.html', {'categories':categories}) def mypage_modify(request): current_category = None categories = Category.objects.all() member = Member.objects.get() if not … -
Django/Docker/Logging: log files are empty
I try to implement logging in my Django project (stack: Django,Docker,Postgresql) It work in my dev environnement but not in preproduction (linux/Debian) I got no error but files are empty I look for permission on files and set chmod 777 to my log files for test but doesn't work neither settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'loggers': { 'django': { 'handlers':['files_info','files_debug'], 'propagate': True, 'level':'INFO', }, }, 'handlers': { 'files_info': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': './logsfiles/info', 'formatter': 'mereva', }, 'files_debug': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': './logsfiles/debug', 'formatter': 'mereva', }, }, 'formatters': { 'mereva': { 'format': '{levelname} {asctime} {module} {message}', 'style': '{', } }, } views.py # Get an instance of a logger logger = logging.getLogger('django') def home(request): authenticated = request.user.is_authenticated if authenticated: print('Connected user',request.user) logger.info('User :{0}'.format(request.user.username)) return render(request, 'home.html') -
How to upload default static file to the ImgeField?
I am trying to upload my default static image if no image input is provided but it is not working. It is just adding the path but actual static image is not uploading. from django.templatetags.static import static def save(self, *args, **kwargs): if not self.image: self.image = static('images/default-img.png') return super().save(*args, **kwargs) -
Django + Nginx + Gunicorn setup with error: (104: Connection reset by peer) while reading response header from upstream
I have a server set up with Ubuntu 20.04, Nginx and running a Django app with Gunicorn. My gunicorn.socket file is like so: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target And My gunicorn.service file is so: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/backend ExecStart=/root/.local/share/virtualenvs/backend-Lu9kB6KY/bin/gunicorn \ --access-logfile /var/log/nginx/backend.log \ --workers 3 \ --bind unix:/run/gunicorn.sock \ backend.wsgi:application [Install] WantedBy=multi-user.target And in a file at /etc/nginx/sites-available/backend, I have: server { listen 80; listen [::]:80; server_name domain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/backend/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } When I visit the homepage, I see a 502 Bad Gateway error, and the logs at /var/log/nginx/error.log shows: [error] 15866#15866: *86 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 82.102.24.9, server: domain.com, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "domain.com" What have I done wrong? What to do? -
What is the most efficient way to store/cache heavy, repetitive operations on the backend?
I am using Django as a web server, and I am encountering a situation where I need to fetch top products from my DB to the memory based on filters, tags, and categories. Then I apply pagination before sending a JSON response to the frontend. The endpoint to this operation is the main feature in my app, hence I'd expect hundreds of the same request each minute. Since I have 10s of thousands of items in my DB, it is causing a lot of load on my system's infrastructure and it's leading to many undesireable drawbacks like slow response time, cost, etc. So the question is, are there any methods to handle temporal caching and storing of common tasks like getting the same list of products periodically in Django? My initial thought is as follows: - implement a periodic function - store the result of the function in some semi-DB - when users request that endpoint/function, it returns (without re-calculation) the paginated response I want to implement the above mentioned system in django, is it doable and what libraries and tool I have to use? I use Python 3.8 and Django 3.0.5 -
Transferring data from uploaded filefield to db (django, sqlite)
I am trying to transfer the data of the filefield files I upload using django to database. All what I am able to do is to upload data and stored in local directory. However, I'd like to save the data into database. The format of the files are principally csv files. models.py class UploadForm(models.Model): file = models.FileField() class Meta: db_table = "db_table" forms.py class UploadForm(forms.ModelForm): class Meta: model = UploadForm fields = "__all__" functions.py def handle_uploaded_file(f): with open('vps_app/static/upload/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) views.py def index(request): if request.method == 'POST': Uploaded = UploadForm(request.POST, request.FILES) if Uploaded.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponse("File uploaded successfuly") else: Uploaded = UploadForm() return render(request, "index.html", {'form': Uploaded}) Help would be enormously appreciated -
Error in Django migrations, no changes detected
I've correctly done the "initial setup" with python manage.py migrate command and now in my mongodb database I see these collections: __schema__ auth_group auth_group_permissions auth_permission auth_user auth_user_groups auth_user_user_permissions django_admin_log django_content_type django_migrations django_session with object inside them so I'm pretty sure that I did it correctly and if I do it now it says: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. I think this is all normal, then i created this models.py file models.py from django.db import models # Create your models here. class Customer(models.Model): name = models.CharField(max_length=200, null=True) surname = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) When I try to do python manage.py makemigrations I get this "No changes detected". Adding my app name doesn't solve the problem. I have a migrations folder with init.py (with the __) in it. I don't understand why it worked for the initial setup and now it doesn't. If i put some syntax error in the models.py file the messages I get after running the commands are the same, so maybe models.py is being searched in another folder? Really don't know, anyway hope i wrote everything necessary, … -
how can i deal with this django problem "AttributeError at /profile/ 'CustomerProfileForm' object has no attribute 'cleaned_date'"
class ProfileView(View): def get(self, request): form = CustomerProfileForm() return render(request, 'profile.html', {'form': form, 'active': 'btn-primary'}) def post(self, request): form = CustomerProfileForm(request.POST) if form.is_valid(): user = request.user.username name = form.cleaned_data['name'] locality = form.cleaned_data['locality'] city = form.cleaned_data['city'] state = form.cleaned_data['state'] zipcode = form.cleaned_data['zipcode'] reg = Customer(user=user, name=name, locality=locality, city=city, state=state, zipcode=zipcode) reg.save(request) messages.success( request, 'Congratulation! profile update successfully') return render(request, 'profile.html', {'form': form, 'active': 'btn-primary'}) -
DjangoRestAPI filter a list field
in my DjangoRestAPI project i have 2 serialisers like this: serializers.py class TagSerializer(serializers.ModelSerializer): class Meta: model = Tags fields = ['tagkey', 'tagval'] def create(self, validated_data): return Tags.objects.create(**validated_data) def update(self, instance, validated_data): instance.tagkey = validated_data.get('tagkey', instance.tagkey) instance.tagval = validated_data.get('tagval', instance.tagval) instance.save() return instance class ModvarSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') var_group = VarGroupSerializer(read_only=True) tag_var = TagSerializer(read_only=True, many=True) class Meta: model = ModbusVariable fields = ['id', 'short_name', 'uom', 'var_group', 'unit', 'writeable', 'value_class', 'address', 'bit_count', 'min_type','max_type', 'byte_order','function_code_read', 'is_quarterly', 'tag_var', 'owner'] def create(self, validated_data): ... well now in my views.py i have to create a ModVar list with a filter also for tag_var value: views.py class ModvarsList(generics.ListCreateAPIView): queryset = ModbusVariable.objects.using(random.choice(replica_list)).all() serializer_class = ModvarSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] pagination_class = StandardResultsSetPagination # paginator = None filter_backends = [DjangoFilterBackend] filterset_fields = { 'unit__port_id__master_id': ['exact'], 'unit__port_id__master_id__short_name': ['exact'], 'is_quarterly': ['exact'], 'tag_var': ['exact'] } search_fields = ['unit__port_id__master_id', 'unit__port_id__master_id__short_name', 'is_quarterly'] ordering_fields = '__all__' so if i run my API caall without filter i get this results: but if i try to filter for example using tag_var="tagkey: site1" or just "site1" i ever get the error The value is not correct for tag_var filter How can i expose just "key" and "value" field of tag_val value for filtering based on that values my API … -
django PostgreSQL arrayfield store a 3 dimension array
this is the list a want to store in my database : [30, 9.45, [3.4499999999999993, 1.0500000000000007], [10.625, 12.875], [14.075, 11.825], [9.0, 15.0], [12.904858299595142, 15.637651821862349], [15.0, 18.0], [1 .0, 1.0], [6.0, 10.5], [10.5, 6.0], [0.0, 0.0], [[3, 6], [3, 6, 6]], [[6.0, 1.5] , [10.5, 6.0, 4.5]], [27.0, 94.5], [110.1141194331984, 106.83476720647775]] my models.py : D240_TOTAL = ArrayField( ArrayField( models.FloatField(max_length=10, blank=True), blank=True, null=True, ), blank=True, null=True, ) but am getting the error : Field 'D240_TOTAL' expected a number but got [3, 6]. because my field is 2-d array but i am giving him a 3d array so how do i fixe that -
Problem when uploading a web made in django to aws
I am followint this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-configure-for-eb When I do: eb deploy I obtain the following error: [2021-07-08T12:48:37.858Z] ERROR [4740] : Command execution failed: Activity failed. (ElasticBeanstalk::ActivityFatalError) caused by: DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6 Collecting APScheduler==3.7.0 (from -r /opt/python/ondeck/app/requirements.txt (line 1)) /opt/python/run/venv/lib/python2.6/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissingwarning. However I have a python version 3.9.5 Thank you -
Django else statement in html template not working
Why my else statement not working in html template. It should be display text "You don't have any notification" if user didn't have any notification. I am using else statement in my html template for showing the text but why text isn't showing? here is my code: {% for notification in notifications %} {%if user.id == notification.blog.author.id %} {% if notification.notification_type == "Comment Approved" %} Your Blog Post {{notification.blog.title}} received new commnet {%else%} <h1>Don't have any notification</h1> {% endif %} {%endif%} {%endfor%} when user don't have any notification I am getting empty html page. If user have notification then it's displaying but I am not understanding why my else statement not working when user don't have any notifications. -
How to make inline form in admin requiring some of the params?
I have the following code in django admin: class MarkFormatInline(admin.TabularInline): model = MarkFormat form = MarkFormatForm fields = ('format', 'url_template', 'start', 'count', 'delay', 'xmltimeout', 'adtimeout', 'only_fire', 'server_timeout') extra = 1 and the following form: class MarkFormatForm(forms.ModelForm): class Meta: widgets = { 'xmltimeout': AdminIntegerFieldWidget(), 'adtimeout': AdminIntegerFieldWidget(), } I need to make the url_template field mandatory non-empty and the only_fire flag mandatory to False. How to implement it in Django? -
Can I save input and output data from dash applications in Django database?
I have created few plotly dash applications and integrated them into my Django web application. I wanted to know if we can save using input and output values in our Django database. Is also possible to load this data into the dash apps? -
Accessing one model from within another in Django many-to-one using ForeignKey
Lets imagine we have two models (many-to-one model). Code below shows that a reporter can have multiple articles class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField(null=True) reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE, null=True) def __str__(self): return self.headline Let's see what I have in my database on this model. # Reporter.objects.all().values() # <QuerySet [ # {'id': 1, 'first_name': 'John', 'last_name': 'Smith', 'email': 'john@example.com'}, # {'id': 2, 'first_name': 'Paul', 'last_name': 'Jones', 'email': 'paul@example.com'} # ]> # Article.objects.all().values() # <QuerySet [ # {'id': 5, 'headline': "1st headline", 'pub_date': datetime.date(2005, 7, 29), # 'reporter_id': 1}, # {'id': 6, 'headline': "2nd headline", 'pub_date': datetime.date(2006, 1, 17), # 'reporter_id': 2}, # {'id': 7, 'headline': '3rd headline', 'pub_date': datetime.date(2005, 7, 27), # 'reporter_id': 1} # ]> The first reporter has two publications and second has the only. I need to get the list of all articles for each reporter. I tried this way (according to django docs): Article.objects.filter(reporter__first_name='John') It's okay. It works. I also tried to instantiate the first reporter as 'r1' and then do this: r1.article_set.all() And this piece of code works too. But as I'm new to django, … -
Heroku can't connect fonts
I have downloaded fonts for html template that is converted with xhtml2pdf to pdf. I didn't manage to google for answer that works for me. I thought that path was changed but in heroku bash path isn't changed. Here is my code: fonts are in invoices/static/invoices/fonts settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'main/static'), #os.path.join(BASE_DIR, 'invoices/static'), #BASE_DIR / "static", ] STATIC_ROOT os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage. CompressedManifestStaticFilesStorage' html font connect <html lang="ru"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html" > <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Инвойс #{{invoice_id}}</title> <style> @font-face { font-family: 'Roboto-Medium'; src: url(../invoices/static/invoices/fonts/Roboto-Medium.ttf); } </style> -
How to run Django migrations inside kubernetes and apply changes to the database pod?
I have deployed my app to Azure with Kubernetes. I have separate pods for front end, back end and database. I encountered problems when one of my database fields changed from id to userId. I have tried to update this change to my deployment database but without any luck. I logged into my back end pod and removed the existing migration file and run python manage.py makemigrations & python manage.py migrate. After these I checked that everything was ok in the migration file. After this I don't know what to do. Do I need to remove the database pod and create it again? Or how do I update the database inside the pod?