Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running django web app over a web path in a sandbox
At the place where I work we have the option to deploy applications through a sandbox. With that a problem arises and that is that for each application running we have a web path, for example: domain.com/path/of/app_django/. With that base path I can access the main view of my application (0.0.0.0:8080/ >> domain.com/path/of/app_django/) however when trying to access other views django uses the main domain, for example domain.com/my_url instead of being domain.com/path/of/app_django/my_url. What can I do to fix this? -
Reduction of queries in ManyToMany field with prefetch_related
I want to reduce further the number of queries. I used prefetch_related decreasing the number of queries. I was wondering if it is possible to reduce to one query. Please let me show the code involved: I have a view with prefetch_related: class BenefitList(generics.ListAPIView): serializer_class = BenefitGetSerializer def get_queryset(self): queryset = Benefit.objects.all() queryset = queryset.filter(deleted=False) qs= queryset.prefetch_related('nearest_first_nations__reserve_id') return qs I have the models used by the serializers. In here, it is important to notice the hybrid property name which I want to display along with reserve_id and reserve_distance: benefit.py: class IndianReserveBandDistance(models.Model): reserve_id = models.ForeignKey(IndianReserveBandName, on_delete=models.SET_NULL, db_column="reserve_id", null=True) reserve_distance = models.DecimalField(max_digits=16, decimal_places=4, blank=False, null=False) @property def name(self): return self.reserve_id.name class Benefit(models.Model): banefit_name = models.TextField(blank=True, null=True) nearest_first_nations = models.ManyToManyField(IndianReserveBandDistance, db_column="nearest_first_nations", blank=True, null=True) Name field is obtained in the model IndianReserveBandName. indian_reserve_band_name.py: class IndianReserveBandName(models.Model): ID_FIELD = 'CLAB_ID' NAME_FIELD = 'BAND_NAME' name = models.CharField(max_length=127) band_number = models.IntegerField(null=True) Then, the main serializer using BenefitIndianReserveBandSerializer to obtain the fields reserve_id, reserve_distance and name: get.py: class BenefitGetSerializer(serializers.ModelSerializer): nearest_first_nations = BenefitIndianReserveBandSerializer(many=True) The serializer to obtain the mentioned fields: distance.py: class BenefitIndianReserveBandSerializer(serializers.ModelSerializer): class Meta: model = IndianReserveBandDistance fields = ('reserve_id', 'reserve_distance', 'name') The above is resulting in two queries which I would like to be one: SELECT ("benefit_nearest_first_nations"."benefit_id") AS … -
Django Channels + Vue + Daphne + Google App engine flex app won't start after deployment
The app loads blank screen, and after inspecting the Network tab in browser I see that only main.css and main.js are requested, no chunk-some_id.js or css files. On top of that the main css and js cause a message in browser console Refused to apply style from 'my_site.appspot.com/static/vue/css/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. I am using custom runtime and here is my app.yaml file: runtime: custom runtime_config: operating_system: "ubuntu18" runtime_version: "3.8" env: flex service: development network: forwarded_ports: - 9000/tcp beta_settings: cloud_sql_instances: db_address env_variables: DB_HOST: "DB_HOST" DB_PASSWORD: 'DB_PASSWORD' DB_NAME: 'DB_NAME' REDIS_HOST: 'REDIS_HOST' REDIS_PORT: 'REDIS_PORT' STATIC_ROOT: 'STATIC_ROOT' DEFAULT_FILE_STORAGE: 'DEFAULT_FILE_STORAGE' STATICFILES_STORAGE: 'STATICFILES_STORAGE' GS_PROJECT_ID: 'GS_PROJECT_ID' GS_BUCKET_NAME: 'GS_BUCKET_NAME' GS_STATIC_BUCKET_NAME: 'GS_STATIC_BUCKET_NAME' STATIC_URL: '/static/' MEDIA_ROOT: 'media' MEDIA_URL: '/media/' UPLOAD_ROOT: 'media/uploads/' DOWNLOAD_URL: "media/downloads" resources: cpu: 1 memory_gb: 5 disk_size_gb: 10 manual_scaling: instances: 1 liveness_check: success_threshold: 1 failure_threshold: 2 I have omitted entrypoint in app.yaml as I understand it is not needed since it is defined in Dockerfile. Here is my Dockerfile: # Use the official Python image as the parent image FROM python:3.8-slim-buster # Set the working directory to /app WORKDIR /app # Install system dependencies RUN apt-get update && apt-get install -y libpq-dev nginx … -
Cancelled Sessions from Student s letting confirmation lapse finding their way into the queue
I'm using django. I'm having an with a website were tutors can connect with students. There is a bug were students who have cancelled there session are still finding there cancelled session back to the queue, I'm seeing the unfulfilled requests has jumped from 34 on Monday to 75 now and I'm wondering how many of those requests are real. I cant find the source code I Cant find the source code and I need to locate it first -
How do I add a Form Object, from the Database, Into the model?
How do I add a Form Object, from the Database, Into the model? models.py class TwoUserModel(models.Model): user1 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) user2 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #Add assigned_number here based on the form below. forms.py class NameForm(forms.Form): assigned_number = models.IntegerField(null=True, blank=True) -
form_valid method not called if post method not overrided
I have a blog that is composed by user's posts and post's comments. In my UpdateView, the model points to Post, so I can show the post in the template. In my form_valid method, I get the comment from the user through a form. The problem is that if I don't override the post method, the form_valid method is not called. When I post something through a form, what happens? What methods are called by django and what methods should I override? class PostDetails(UpdateView): template_name = "posts/details.html" model = Post form_class = CommentForm context_object_name = 'post' # success_url = "posts/details.html" def form_valid(self, form): post = self.get_object() comments = Comments(**form.cleaned_data) comments.post = Post(post.id) if self.request.user.is_authenticated: comments.user = self.request.user comments.save() messages.success(self.request, "Post sent successfully") return redirect("posts:details", pk=post.id) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = self.get_object() comments = Comments.objects.filter(published=True, post=post.id) context['comments'] = comments return context class CommentForm(ModelForm): def clean(self): data = super().clean() author = data.get("author") comment = data.get("comment") if len(comment) < 15: print("Entrou no if do comment") self.add_error("comment", "Comment must be 15 chars or more.") if len(author) < 5: self.add_error("author", "Field must contain 5 or more letters.") class Meta: model = Comments fields = ['author', 'email', 'comment'] {% extends 'base.html' %} {% … -
please help me! when i run the code thes errors apear in my python and django project
MS yacine@yacine-Lenovo-ideapad-110-15IBR:~/Desktop/LMS/LMS$ python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 04, 2023 - 18:37:16 Django version 4.2, using settings 'LMS.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [04/May/2023 19:10:58] "GET / HTTP/1.1" 200 403643 Not Found: /api.mapbox.com/mapbox-gl-js/v0.53.0/mapbox-gl.css [04/May/2023 19:10:58] "GET /api.mapbox.com/mapbox-gl-js/v0.53.0/mapbox-gl.css HTTP/1.1" 404 3077 Not Found: /api.mapbox.com/mapbox-gl-js/v0.53.0/mapbox-gl.js [04/May/2023 19:10:59] "GET /api.mapbox.com/mapbox-gl-js/v0.53.0/mapbox-gl.js HTTP/1.1" 404 3074 Not Found: /assets/js/theme.min.js [04/May/2023 19:21:01] "GET /assets/img/menu/home-v7.jpg HTTP/1.1" 404 3011 Not Found: /assets/img/menu/home-v11.jpg [04/May/2023 19:21:01] "GET /assets/img/menu/home-v9.jpg HTTP/1.1" 404 3011 [04/May/2023 19:21:01] "GET /assets/img/menu/home-v11.jpg HTTP/1.1" 404 3014 Not Found: /assets/img/menu/home-v12.jpg note:all file are in the right place -
How to read byte strings generated by marshall on the jquery side?
On the Django server side, I form a response: def index(request): if request.method == 'POST': ... url = reverse(settlement_create, args=[settlement_id]) return HttpResponse(marshal.dumps({'url': url}), content_type="application/json") , where url=/settlement/154/create. jQuery cannot decode the byte string correctly and it turns out {� url� /settlement/154/create0. $.ajax({ type : 'POST', url : url, data : {'text': city_info}, success : function(response){ $("#city-href").attr('href', response['url']); }, error : function(response){ console.log(response) } }); If you use a regular json library instead of marshal, then everything works fine. Do you have any ideas? -
checkmark is not shown in django form
I created contact form but checkmark is not showing the option and the box is very narrow. So when login as admin and try to add a contact, I don't see options in there. Here is models.py and forms.py and screenshot. models.py class Location(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Contact(models.Model): LOCATION_INHOME = ( ('kitchen', 'Kitchen'), ('bathroom', 'Bathroom'), ('bedroom', 'Bedroom'), ('livingroom', 'Living Room'), ('basement', 'Basement'), ('garage', 'Garage'), ('office', 'Office'), ('hallway', 'Hallway'), ('stairway', 'Stairway'), ('recreationroom', 'Recreation Room'), ('closet', 'Closet'), ('other', 'Other'), ) location_in_home = models.ManyToManyField(Location) class ContactForm(ModelForm): model = Contact fields = '__all__' class Meta: model = Contact fields = '__all__' forms.py from django import forms from django.forms import ModelForm from .models import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact fields = [ 'location_in_home', ] widgets = { 'location_in_home': forms.CheckboxSelectMultiple(), } Here is the admin.py class ContactAdmin(admin.ModelAdmin): list_filter = ('location_in_home') admin.site.register(Contact, ContactAdmin) -
Django querysets: how to combine two querysets in django one is based on Form and 2nd is based on Q objects
this is my view function as i have a problem to get docks = Docks.objects.filter(Q(dock_1__icontains=query)) to protein.html page.I have two queries one from SearchForm related to Proteins model and other is from Q objects and i want to get both fields pdb_name and dock_1 but i am only getting one pdb_name with its related parameters from Proteins model only but didnot get dock_1 from Docks model. class SearchForm(forms.Form): """Search view showing the top results from the main page of the AMPdb tool.""" query_id = forms.CharField() def create_query(self): """the form fields get put into self.cleaned_data, make a new PDBQuery object from those fields and return""" query = Proteins(name=self.cleaned_data["pdb_name"]) query.save() return query` class SearchView(generic.FormView): """Search view of the AMPdb tool.""" form_class = SearchForm template_name = "abampdb/search.html" success_url = "/" def get_context_data(self, **kwargs): context = super(SearchView, self).get_context_data(**kwargs) query = self.request.GET.get('q', '') category = self.request.GET.get('category', '') docks = Docks.objects.filter(Q(dock_1__icontains=query)) context = {} rows = [] for peptide in itertools.zip_longest(Proteins.objects.all()): rows.append({ 'left': peptide, }) context['rows'] = rows context['proteins'] = Proteins.objects.all() context['dock'] = docks context['query'] = query context['category'] = category try: context["protein"] = Proteins.objects.get( name=self.request.GET.getlist("pdb_name") ) except Proteins.DoesNotExist: context["protein"] = None print(context) return context # return self.render_to_response(context) def form_valid(self, form): params = { "pdb_name": form.cleaned_data.get('pdb_name'), "dock_1": … -
removing added django application from a database
I just posted another question: Django error on deleting a user in the admin interface But realized in that question the project /models it is complaining about I am going a different direction with. So I was curious how I can I just remove a project from the database. i.e. a whole folder under my django application? I will be redoing it anyway and I want my deployed application from the earlier question to keep working along. Is it just a matter of removing all the data in models.py and then doing a new migration? -
The field '' was declared on serializer Serializer, but has not been included in the 'fields' option
I am working on aproject with django and DRF. I am facing this error AssertionError at /barber/info/ The field 'comments' was declared on serializer BarberSerializer, but has not been included in the 'fields' option. I dont know why am I facing this error despite I already have added 'comments' in my fields. this is my serializer: class BarberSerializer(serializers.ModelSerializer): comments = CommentSerializer(many=True) rating = serializers.SerializerMethodField(source= "get_rating") customers_rate = serializers.SerializerMethodField() # comments = serializers.SerializerMethodField() # rating = serializers.SerializerMethodField() # comment_body = serializers.CharField(write_only=True, required=False) class Meta: model = Barber fields = ('id','BarberShop','Owner','phone_Number','area','address','rate', "rating", "customers_rate", 'background','logo', 'comments', )# ,"comment_body", ]# "rating"] read_only_fields = ("id", "created_at", "BarberShop", "Owner", "phone_Number", "area", "address" , 'background','logo',"comments", "rate", "rating", "customers_rate") def get_comments(self, obj): comments = obj.comments.all() serializer = CommentSerializer(comments, many=True, context=self.context) return serializer.data def get_rating(self, obj): comments = obj.comments.all() if comments: ratings = [comment.rating for comment in comments] return sum(ratings) / len(ratings) return 0 def get_rating(self,obj): ratings = obj.ratings.all() if ratings : ratings = [rating_instance.rating for rating_instance in ratings] # print(*ratings, sep = "\*n") return round(sum(ratings) / len(ratings), 2) else: return 3.33 def get_customers_rate(self, obj): customer = self.context['request'].user.customer # print(customer, sep = "*****\n") try: rating = obj.ratings.filter(customer=customer).order_by("-created_at").first() # rating = Rating.objects.get(customer= customer, barber = obj) return rating.rating except: return … -
Error: Unknown field(s) (username) specified for User. Check fields/fieldsets/exclude attributes of class CustomUserAdmin
So I created a CustomUserAdmin, so that I can use Email instead of using default username. This is my code. model.py class User(AbstractUser): username = None email = models.EmailField(unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = UserManager() admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from core.models import User from django.contrib.auth import get_user_model class CustomUserAdmin(UserAdmin): list_display = ("email", "first_name", "last_name", "is_staff") search_fields = ("email", "first_name", "last_name") ordering = ("email",) add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ( "email", "first_name", "last_name", "password1", "password2", ), }, ), ) admin.site.register(get_user_model(), CustomUserAdmin) When I tried to add or modify a User in Admin Page, this Traceback appeared: Internal Server Error: /admin/core/user/4/change/ Traceback (most recent call last): File "D:\BaiTap\C#\fashion_shop\src\backend\env\lib\site-packages\django\contrib\admin\options.py", line 809, in get_form return modelform_factory(self.model, **defaults) File "D:\BaiTap\C#\fashion_shop\src\backend\env\lib\site-packages\django\forms\models.py", line 642, in modelform_factory return type(form)(class_name, (form,), form_class_attrs) File "D:\BaiTap\C#\fashion_shop\src\backend\env\lib\site-packages\django\forms\models.py", line 321, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (username) specified for User During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\BaiTap\C#\fashion_shop\src\backend\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\BaiTap\C#\fashion_shop\src\backend\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\BaiTap\C#\fashion_shop\src\backend\env\lib\site-packages\django\contrib\admin\options.py", line 688, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) ModelForm = self.get_form( File "D:\BaiTap\C#\fashion_shop\src\backend\env\lib\site-packages\django\contrib\auth\admin.py", line 98, … -
How can I display django form in modal window on homepage?
The form works correctly in a register.html file but when I put inside the modal window on my home page the fields aren't displayed and the button doesn’t actually work. My home.html file: {% load i18n %} <!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <title>{% trans 'Блог страдальцев' %}</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> </head> <body> <div class="g-image"; style="background-image: linear-gradient( 112.1deg, rgba(32,38,57,1) 11.4%, rgba(63,76,119,1) 70.2% ); min-height: 100vh"> <header> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="/">{% trans 'Блог страдальцев' %}</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Переключатель навигации"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/">{% trans 'Главная' %}</a> </li> <li class="nav-item"> <a class="nav-link" href="/about">{% trans 'О блоге страдальцев' %}</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> {% trans 'Разделы блога' %} </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="/pozn">{% trans 'Страдальческий' %}</a></li> <li><a class="dropdown-item" href="/len">{% trans 'Не страдальческий' %}</a></li> <li> <hr class="dropdown-divider"> </li> <li><a class="dropdown-item" href="/superlren">{% trans 'Очень страшно' %}</a></li> </ul> </li> <form action="{% url 'search_results' %}" method="get"> <input name="q" type="text" placeholder="Search..."> </form> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal"> Окошечко </button> <!-- Модальное окно --> <div … -
Download all the processed files generated on the fly as zip file on client side (without saving processed files on Server/Database) in Django Python
I want to download all the processed files generated in a program as a zip file on client system on the fly without storing them on the server/database side. I am working on Django framework. The idea is to take multiple files as input from the user, perform some processing on excel files and then download those files as a single zipfile (on the fly) at the client end without storing them on server To achieve this, what I did is: **In my views.py file:** from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import zipfile import pandas as pd import io # creating a zip file object outside any function so that its accessible to all the functions in the views.py file (**Not sure if this is the right way of doing it**) zipObj = ZipFile('sample.zip', 'w') # This function identifies if the file is excel def myfiletype(fname): filename = fname # Get file extension file_ext = filename.split(".")[-1] # check if extension matches type of file we expect: if file_ext.lower() in ("xls", "xlsx"): return "excel" return "unrecognized" @csrf_exempt def files_processing(request): if request.method == "POST": files = request.FILES.getlist('file') # process each file: for file in files: if myfiletype(str(file)) == 'excel': excel_processor(file) … -
Django error on deleting a user in the admin interface
Somewhere between my development machine and my deployment machine (still in testing thank god), the migrations got jumbled. I am not sure what is going on or how to fix, I found the error just by simply going to the admin and deleting a user. I think the migrations got jumbled between my development box and deployment box (thats still in testing thank god) The error I get when I try to delete the user is in debug.log and it says: django.db.utils.ProgrammingError: column programscheduler_proposal.program_id does not exist LINE 1: SELECT "programscheduler_proposal"."id", "programscheduler_p... ^ HINT: Perhaps you meant to reference the column "programscheduler_proposal.programID". So the models being referenced are: class Proposal(models.Model): objects = models.Manager() program = models.ForeignKey("Program", on_delete=models.CASCADE) institution = models.ForeignKey("mainpage.Institution", on_delete=models.CASCADE) title = models.CharField(max_length=100) scheduler = models.ForeignKey('accounts.APOUser', on_delete=models.CASCADE) pi = models.ForeignKey('accounts.APOUser', related_name='%(app_label)s_%(class)s_related', on_delete=models.PROTECT) #observers recahback to proposal observer. untrained_observer_list = models.CharField(max_length=200) #just seperate via commas collaborators = models.CharField(max_length=200) #just seperate via commas ... ... class Program(models.Model): programName = models.CharField(max_length=100) institution = models.ForeignKey("mainpage.Institution", on_delete=models.CASCADE) Then under accounts class APOUser(models.Model): objects = models.Manager() user = models.OneToOneField(User, on_delete=models.CASCADE) institution = models.ForeignKey("mainpage.Institution", on_delete=models.SET_NULL, null=True) gender = models.ForeignKey("mainpage.GenderTable", on_delete=models.SET_NULL, null=True) on_site_status = models.ForeignKey("mainpage.SiteStatus", on_delete=models.SET_NULL, null=True) refer_to_as = models.TextField(max_length = 30, blank=True, null=True) #if the above … -
Sending files with Web socket
I want to create a chat using web socket (django-channels). And I have a problem, when I try to upload file data about him goes into a variable text_data in receive() function. Maybe It's more problems with code, and i will be grateful for any help. Here is a code chat_room.js: const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); chatSocket.onerror = function(event) { document.querySelector('body').innerHTML = '<h1>Chat does not exist</h1>'; }; chatSocket.onmessage = function(e){ console.log(1) const data = JSON.parse(e.data); if (data.message){ console.log(2) let messange = document.createElement('li') messange.textContent = data.message document.querySelector('.chat-log-list').appendChild(messange); } else if(data.file){ console.log(3) let message = document.createElement('li') let link = document.createElement('a') link.textContent = data.file.filename; link.href = data.file.url link.target = '_blank' message.appendChild(link) document.querySelector('.chat-log-list').appendChild(messange); } } chatSocket.onclose = function(e){ console.error('Chat socket closed unexpectedly'); }; document.querySelector('#chat-message-input').focus(); document.querySelector('#chat-message-input').onkeyup = function(e) { if(e.keyCode === 13){ document.querySelector('#chat-message-submit').click(); } } document.querySelector('#chat-message-submit').onclick = function(e){ const messageInputDom = document.querySelector('#chat-message-input'); const message = messageInputDom.value const fileInputDom = document.querySelector('#chat-file-input'); const file = fileInputDom.files[0] if (file){ const reader = new FileReader(); reader.onload = (event) => { const fileData = event.target.result; chatSocket.send(JSON.stringify(fileData)) } reader.readAsDataURL(file) } else if(message){ chatSocket.send(JSON.stringify({ 'message': message })); } fileInputDom.value = '' messageInputDom.value = ''; } consumers.py: import json from .models import * … -
Django NoReverseMatch Solution?
I am carrying out a project for an online grocery store. I want to have a 'View Ratings' button beneath each item within the store that takes users to a ratings.html page where they can view previous ratings and also submit their own using a form. However, I am running into the following error when I attempt to click the 'View Ratings' button beneath an item. Also, if i managed to get this fixed, is there a way I can make it so I can view the ratings in my admin area. Any help appreciated! Reverse for 'ratings' with arguments '('',)' not found. 1 pattern(s) tried: ['ratings/(?P<item_id>[0-9]+)/\\Z'] Request Method: GET Request URL: http://localhost:8000/ratings/1/ Django Version: 4.1.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'ratings' with arguments '('',)' not found. 1 pattern(s) tried: ['ratings/(?P<item_id>[0-9]+)/\\Z'] Exception Location: C:\Users\Sammc\OneDrive - Ulster University\Desktop\django_project\venv\lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix Raised during: customer.views.Ratings Python Executable: C:\Users\Sammc\OneDrive - Ulster University\Desktop\django_project\venv\Scripts\python.exe Python Version: 3.10.7 Python Path: ['C:\\Users\\Sammc\\OneDrive - Ulster ' 'University\\Desktop\\django_project\\groc', 'C:\\Python310\\python310.zip', 'C:\\Python310\\DLLs', 'C:\\Python310\\lib', 'C:\\Python310', 'C:\\Users\\Sammc\\OneDrive - Ulster ' 'University\\Desktop\\django_project\\venv', 'C:\\Users\\Sammc\\OneDrive - Ulster ' 'University\\Desktop\\django_project\\venv\\lib\\site-packages'] Server time: Thu, 04 May 2023 14:54:43 +0000 Error during template rendering In template C:\Users\Sammc\OneDrive - Ulster University\Desktop\django_project\groc\customer\templates\customer\ratings.html, error at line 15 Reverse for … -
Static css is not implementing in django templates
I made this project for my own learning about 2 months back. That time all things were working properly . After that today, I again ran this project but this time static css is not being applied on templates. I could not find any issue. Please help me with this. This is the folder outlet This is the setting code This is base template code that is extended in other html -
i dont know How to fil out and 'priant' a convocation IN DJANGO?
hi i have a problème in Django i dont know How to fil out and 'print' a convocation IN DJANGO ? I dont know how start the problem. I do some 'recherche' but no one talk about this problem -
500 Error When Accessing robots.txt File in Django App Hosted on HestiaCP: Need Help Fixing the Issue
I just tried to publish web-site using the Django App, the organization gave me the HestiaCP for host it. Everything works grate, but I have one and only problem. When I tryed to get the robots.txt file it gives me the 500 error. It still work correctly when I run it on the localhost. enter image description here enter image description here Hestia gave me that log: 353868 could not find named location "@fallback", client: ***.***.***.***, server: *************.***, request: "GET /robots.txt HTTP/1.1", host: "*****************.***" I hide the ip and site name by the *. Sorry for that. But still. I thought that its not a problem when Bing index that page, but when I goes into Google search console... It even cant parse the sitemap.enter image description here Have someone know what I should to do? I have no idea how to fix it. But here you can give me some useful tips for fix it. I hope someone know how fix it. -
Error message for deploying Django app to Azure
Is anyone able to explain why I'm getting this error message when trying to deploy my django-python app to Azure via the VS Code Azure Tool Extension? "This region has quota of 0 instances for your subscription. Try selecting different region or SKU." I'm on a free trial with Azure. I followed the instructions from this tutorial https://learn.microsoft.com/en-us/training/modules/django-deployment/6-deploy-azure but have not been able to proceed past the 'create web app' stage. -
Module not found error in Python script running as a Windows Service
I have a Django "learning project" which hosts a very simple web site, with waitress providing the WSGI server. The project performs as expected when I execute the calling script from the command line. From here I'm trying to set up the scaffolding to have it run as a Windows Service. I installed pywin32 and servicemanager to my virtual environment, and -- later on, trying to resolve an error -- also installed them to my "real" Python instance on the machine. Despite this, I keep getting a ModuleNotFoundError error, citing servicemanager, when I try to start the created service: This Python script I'm using; it is based on a template script I found here. import win32serviceutil import win32service import win32event import servicemanager import socket from waitress import serve from django_project.wsgi import application class AppServerSvc (win32serviceutil.ServiceFramework): _svc_name_ = "PagesService" _svc_display_name_ = "Pages Service" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main() def main(self): serve(application, port='8000') if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) As noted above I've installed servicemanager to both the virtual environment and the "real" environment, I've followed the classic Roy request and rebooted the machine just to be sure. Here's the requirements.txt … -
Trying to Debug Dynamic Forms in Django - logging SQL
Context: I've recently taken on Web Development responsibilities at my job. I'm not 100% familiar with Django or our codebase yet. Our staff intranet has dynamic forms for different accident reports. We have a non-employee accident report that functions perfectly, and an employee accident form that is currently not functioning. The code is nearly identical less a few different fields for each. When the form is submitted, the page will provide a summary of the info you entered to be approved for publication. This works on the non-employee form, but not on the employee form. When I submit the bugged form, the form data exists in the payload and the post request returns a 200 response. At this point we are thinking that it is a database issue, but there isn't any debugging implemented. We are trying to implement some debugging, but I can't get anything to display in the console, though I do think I am pretty confused. IMPORTANT NOTE: We are on a super outdated version of django: 1.11 This is what I have in my settings.py file. Everything I have found and read online says that this should print SQL statements to the console. But I'm not … -
Case-insensitive collation for django field
After upgrading to django 4.2, I changed an email field from CIText into TestField with db collation. However, after the update the field does not seem to be case insensitive (for example querying by email "example@example.com" returns an instance and querying by email "Example@example.com" does not) Here's what I did: Created a new db collation for CI operations = [ CreateCollation( name="case_insensitive", provider="icu", locale="und-u-ks-level2", deterministic=False, ) ] Changed the field from a CITextField to a TextField with the new collation and applied this change's migration email = models.TextField( max_length=255, db_index=True, db_collation="case_insensitive", ) I am using Postgres 12 What else is needed to define a field as a CI? Thanks!