Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unable to retrieve the refresh data from django view to html
I have issue fetching the data to html with Ajax , however I am getting correct output in my django view. Scenario: I have two filter on webpage 1st is to select the Project and 2nd is date range. 1st Scenario: whenever I am selecting the project I am able to get proper output to webpage but whenever I am trying to select the dates with project , I am able to get the output in my django view but not able to fetch the same to HTML. below is the script I am trying for ajax. <script> document .getElementById("inputproject") .addEventListener("change", function () { document.getElementById("project-form").submit(); }); //Date range as a button $("#daterange-btn").daterangepicker( { ranges: { {% comment %} Today: [moment(), moment()], {% endcomment %} Yesterday: [moment().subtract(1, "days"), moment().subtract(1, "days")], "Last 7 Days": [moment().subtract(6, "days"), moment()], "Last 30 Days": [moment().subtract(29, "days"), moment()], "This Month": [moment().startOf("month"), moment().endOf("month")], "Last Month": [ moment().subtract(1, "month").startOf("month"), moment().subtract(1, "month").endOf("month"), ], }, startDate: moment().subtract(29, "days"), endDate: moment(), }, function (start, end) { // Update the selected date range in the span element $("#selected-range").html( start.format("YYYY-MM-DD") + " - " + end.format("YYYY-MM-DD") ); // Get the selected project from the form const project = $("#inputproject").val(); // Create an object with … -
Djang-select2 breaking adaptive page
Im using django-select2 and i have 2 loading js files "select2.full.min.js" and "django_select2.js" and if they`re both enabled it breaks my adaptive page and i got this: If i turn off one of them in chrome developer tools pages works fine but i cant understand what`s the problem Im loading this with form.media.js template.html {% block content %} {{ form.media.css }} <div class="container mt-3"> <form action="{% url 'create_worklog' %}" method="post"> {% csrf_token %} <p class="mb-3">{{ form.worklog_date.label }}:</p> <div class="input-group " id="id_worklog_date" data-td-target-input="nearest" data-td-target-toggle="nearest"> {% render_field form.worklog_date|add_class:"form-control" type='text' data-td-target="#id_worklog_date" %} <span class="input-group-text" data-td-target="#id_worklog_date" data-td-toggle="datetimepicker"> <i class="fas fa-calendar"></i> </span> </div> <div class="mt-3 mb-3"> <p class="mb-3">Контрагент:</p> {% render_field form.contractor_counter|add_class:"w-100" %} </div> <div class="mt-3 mb-3"> <p class="mb-3">Объект:</p> {% render_field form.contractor_object|add_class:"w-100" %} </div> <div class="mt-3 mb-3"> <p class="mb-3">Разделы:</p> {% render_field form.contractor_section|add_class:"w-100" %} </div> <div class="mt-3 mb-3"> <p class="mb-3">Описание:</p> {% render_field form.description|add_class:"form-control" %} </div> <div class="form-footer text-center"> <button type="submit" class="btn btn-primary w-50">Создать</button> </div> </form> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> {{ form.media.js }} {% endblock %} -
Django inline formset missing_management_form error when deleting item
I am using an inline formset in a Django project and I keep getting a "missing_management_form" error when I submit the form. This happens only when I trying to delete item and hit Save button, it works well if I add new items. Exact error message: {'missing_management_form': 'ManagementForm data is missing or has been tampered with. Missing fields: %(field_names)s. You may need to file a bug report if the issue persists.'} Here is my code: # views.py from django.views.generic.edit import CreateView, UpdateView from django.db import transaction from django.urls import reverse_lazy, reverse from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin from django.shortcuts import get_object_or_404 from .forms import OrderForm, OrderItemFormset from .models import Order, OrderItem class OrderCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Order form_class = OrderForm template_name = 'add_order.html' success_message = "Order created successfully!" def form_valid(self, form): context = self.get_context_data() order_item_formset = context['order_item_formset'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if order_item_formset.is_valid(): order_item_formset.instance = self.object order_item_formset.save() return super().form_valid(form) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: order_item_formset = OrderItemFormset(self.request.POST, instance=self.object) else: order_item_formset = OrderItemFormset(instance=self.object) data['order_item_formset'] = order_item_formset return data def get_success_url(self): return reverse('edit_order', kwargs={'pk': self.object.pk}) class OrderUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = Order form_class = OrderForm template_name = 'edit_order.html' success_message = "Order updated … -
is virtual environment only for development or even for running application
I am using ubuntu 22.04 with python 3.10.6 version. My Django application currently works on python 3.7 version and it gives issues in 3.10 version. I want to use virtual environment with python 3.7 version to make application run. If i run the application with Gunicorn for production, will it run 3.7 version of virtual environment of machine version of 3.10? My project uses Gunicorn, nginx and django. -
I am facing this issue in django framework
-while I am making a project in django django -admin startproject hello -I am facing this issue in django , while using this command server is not working -python manage.py runserver -server show this error: -python: can't open file 'manage.py': [Errno 2] No such file or directory -
How to get the date of last change from multiple Django models?
The environment is Django 4 and Python 3.10+. In the application there are multiple data models, each with 'created' and 'modified' DateTimeFields. I need to get the timestamp of last data modification - either creation of new object or modification of a existing one, for cache invalidation. Currently the code checks for the newest creation timestamp and is like this: from django.db.models import Max qs_1 = Model_1.objects.all() qs_2 = Model_2.objects.filter(active=True).order_by('created') qs_3 = Model_3.objects.filter(active=True).order_by('created') last = max(list((itertools.chain(list(queryset.aggregate(Max('created')).values()) for queryset in (qs_1, qs_2, qs_3) if queryset.count()))))[0] My questions are as follows: The expression to get the last creation date is quite convoluted. Is there a way to compute the latest timestamp over multiple models using the ORM alone? It can be done in pure SQL, so it should be possible in the ORM. How do I extend it to also compare the modified fields of the models? -
How can I access and insert values into a database in django?
This is my code: import sqlite3 def add(email, password): conn = sqlite3.connect('database.sqlite3') conn.execute(f"""insert into Users('email', 'password') Values('{email}', '{password}')""") conn.commit() conn.close() @csrf_exempt def save_enq(request): if request.method == 'POST': email = request.POST.get('email') passw = request.POST.get('password') add(email, passw) print("Done!") return render(request, 'index.html') # there is more code but it is irrelevant This is my DB: And this is my error: please help me, I am new to programming. Thank you. :) -
Is there any way to change python version in virtual environment on Windows PC?
The Python version of my windows pc is 3.10.9 but Client's live project python version is 3.8.0. I installed python 3.8.0 for the project but all the other project that I made with python3.10.9 got error. To use many version of python at windows pc is complicated you know. So I want to know is there any option to change my python in virtual environment for the project if I will install again python3.10.9? -
Django Forms two models with foreign key
I am trying to implement the booking function in my Django project. I have two models, one for the customer (Fordonsregister) and one for the service (FordonsService), a one to many relationship as one customer (ID is vehicle registration number: "regnr" which is the primary key in the customer model and the foreign key in the service model (code below). When a customer wants to book they click on a certain service (generated from the service types model (ServiceTypes, below) and get redirected by the urls.py to that specific service url. I would then like the customer to fill out only certain fields. The customer should only fill out the primary key, the foreign key in the form should be auto filled. the "typ" in the service model should be autto filled as the URL is different for the chosen service type. The models: from django.db import models # Create your models here. class Fordonsregister(models.Model): regnr = models.CharField(max_length=6, primary_key=True, null=False, blank=False) namn = models.CharField(max_length=255, null=True, blank=True) tel = models.CharField(max_length=255, default='070-000 00 00', null=True, blank=True) email = models.EmailField(null=True, blank=True) kund_sedan = models.DateTimeField(auto_now=True) kund_points = models.IntegerField(default=0) def __str__(self) -> str: return self.regnr class Meta: ordering = ['regnr'] verbose_name = 'Kunder' verbose_name_plural = … -
I can't load a .joblib file to my views.py on my django project
My .joblib file is in the same directory as views.py literally next to each other but views.py cannot load it and once I runserver FileNotFoundError is thrown. from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt import joblib @csrf_exempt def test(response): if response.method == 'POST': age = int(response.POST['age']) gender_str = str(response.POST['gender']) if gender_str == 'Male': gender_value = 1 else: gender_value = 0 openness = int(response.POST['openness']) neuroticism = int(response.POST['neuroticism']) conscientiousness = int(response.POST['conscientiousness']) agreeableness = int(response.POST['agreeableness']) extraversion = int(response.POST['extraversion']) personality_values_1 = [[gender_value, age, openness, neuroticism, conscientiousness, agreeableness, extraversion]] theModel = joblib.load('PersonalityTestLogisticRegression.joblib') prediction = theModel.predict(personality_values_1) prediction_value = prediction[0] return render(response, "main/Review_Test.html", {'prediction':prediction_value}) I tried everything I can and I'm new to django. Pulling my hair rn. -
Cannot assign member "image_url" for type "Article" "Literal['http://default']" is incompatible with "property"
impot_data: from blog.models import Article def run(): for i in range(5,15): article= Article() article.title="Article num° #%d" % i article.desc="description article num° #%d" % i article.image_url ="http://default" print("opération réussie ") -
django.db.utils.OperationalError: no such column: users_classroom.class_code When attempting to Migrate
This is my first Django project, and I am attempting to add the attribute class_code to Classroom, and class_code is a random 6 character string that I plan to use to allow users to join a classroom using it. I attempted to make it random using the code from the following post:https://stackoverflow.com/a/67546412/20015529 and followed this django document:https://docs.djangoproject.com/en/4.1/howto/writing-migrations/#migrations-that-add-unique-fields. I modified the instructions to use the random string as opposed to a uuid due to the length of uuid's. When attempting to migrate, I recieve the following error: "django.db.utils.OperationalError: no such column: users_classroom.class_code". Here are my Django Files. my project name is Project and the app name is users. Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile, Classroom from home.models import Announcements class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def clean_email(self): email = self.cleaned_data['email'] # if User.objects.filter(email=email).exists(): # raise forms.ValidationError('That email is in use. Please Log in or use a different Email') return email class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] class ClassJoinForm(forms.ModelForm): class Meta: model = … -
changing the src of an image using javascript for a django website
I'm creating a website using django. At the front end I want to change slides every x seconds. My approach was to change the src of the image every x seconds using javascript Here's how I went about it: //Javascript function newSlide() { var imageTemplate = document.querySelector(".slide-img"); setInterval({ imageTemplate.setAttribute("src", "{% static 'images/newSlideImage.png' %}") }, x); } <!-- html --> <img class="slide-img" src="image.png"> I thought this would change the image for me but it didn't work at all. When I checked my console, it said I couldn't load the file and returned 404 error. error: "failed to load resource: the server responded with a status of 404 (Not Found)" However the initial image loaded perfectly despite using the same syntax {% %} -
failure to deploy by django webapp on heroku
Good day, I'm trying to deploy by django webapp on heroku but i'm facing the following problem. The conflict is caused by: The user requested botocore==1.23.50 awsebcli 3.20.3 depends on botocore<1.24.0 and >1.23.41 boto3 1.26.59 depends on botocore<1.30.0 and >=1.29.59 To fix this you could try to: 1. loosen the range of package versions you've specified 2. remove package versions to allow pip attempt to solve the dependency conflict ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts ! Push rejected, failed to compile Python app. ! Push failed And my requirement.txt is the following... asgiref==3.6.0 awsebcli==3.20.3 boto3==1.26.59 botocore==1.23.50 cement==2.8.2 certifi==2022.12.7 charset-normalizer==2.0.12 colorama==0.4.3 contourpy==1.0.7 cycler==0.11.0 distlib==0.3.6 dj-database-url==1.2.0 Django==4.1.4 django-crispy-forms==2.0 django-heroku==0.3.1 django-storages==1.13.2 filelock==3.9.0 fonttools==4.38.0 future==0.16.0 gunicorn==20.1.0 idna==3.4 jmespath==0.10.0 kiwisolver==1.4.4 matplotlib==3.6.3 numpy==1.24.1 packaging==23.0 pathspec==0.9.0 Pillow==9.4.0 platformdirs==2.6.2 psycopg2==2.9.5 psycopg2-binary==2.9.5 pyparsing==3.0.9 python-dateutil==2.8.2 PyYAML==5.4.1 requests==2.26.0 s3transfer==0.6.0 semantic-version==2.8.5 six==1.14.0 sqlparse==0.4.3 termcolor==1.1.0 tzdata==2022.7 urllib3==1.26.14 virtualenv==20.17.1 wcwidth==0.1.9 whitenoise==6.4.0 What am i missing? -
Current path does not match path patterns error
I'm pretty new to Django and I've been following this page step-by-step: https://docs.djangoproject.com/en/4.1/intro/tutorial01/. However, when I try to call the polls app using localhost:8000/polls, a page not found error shows up. I don't have too much of an idea how to fix this, since I'm pretty new. I remember seeing how VS was complaining about the module admin not working but I resolved it by just reinstating the python interpreter. I also tried to re=run the server and reloading VS but it didn't really help. All of my modules match the one in the tutorial. -
Using custom queries with Django annotate
In annotate. When counting records, how can I use a custom query to narrow down what to count? class User(models.Model): name = models.CharField(max_length=50) class Tweet(models.Model): user = models.ForeignKey("User", related_name="tweet") favorite = models.IntegerField(default=0) is_active = models.BooleanField(default=False) objects = TweetQuerySet.as_manager() class TweetQuerySet(models.QuerySet): def buzzed(self): return self.filter( is_active=True, favorite__gte=100 ) # I want to count only the tweets returned using the buzzed query. users = User.objects.annotate(tweet_count=Count("tweet")) Thanks in advance. -
message.success not showing
I'm trying to set up success messages for whens u user successfully logs in. But it is not working for me. I Have tried both in and out of block, both don't work. View: def UserLogin(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request,("You were successfully logged in...")) return redirect('home') else: messages.success(request, ("There was an error logging in, please try again...")) return redirect('login') return render(request, 'registration/login.html', {}) Main.html: {% if messages %} {% for message in messages %} <div class="alert alert-warning alert-dismissible fade show alert-main" role="alert"> <p style="color: darkgreen;">{{ message }}<p> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endfor %} {% endif %} {% block content %} {% endblock %} -
Cant loging in django app service using auth
I develope a website using django, nginx and docker in an azure container registry and app service. when i run the image using docker desktop it runs properly, but when i try to login in appservice in only redirect me to login page. I want to use the default database of django proyect. I am using a simple auth as follow from django.contrib.auth.decorators import login_required @login_required def home(request): username = request.user.username context = {'username': username} return render(request, 'Home/home.html', context) I added in my settings the follow AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', ] AUTH_USER_MODEL = 'auth.User' ROOT_URLCONF = 'sitioindicadores.urls' and also CSRF_TRUSTED_ORIGINS = ['https://*.abc.net/','https://*.127.0.0.1'] SESSION_COOKIE_DOMAIN='https://abc.azurewebsites.net/' my nginx and docker are: server web:8000; } server { listen 80; location / { proxy_set_header Host $host; proxy_pass http://app_server; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /static/ { autoindex on; alias /app/static/; } } and FROM python:3.10 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY sitioindicadores . RUN pip install -r requirements.txt COPY nginx.conf /etc/nginx/sites-available/default RUN python manage.py collectstatic --noinput && python manage.py makemigrations && python manage.py migrate EXPOSE 80 CMD ["gunicorn", "--bind", "0.0.0.0:80", "sitioindicadores.wsgi:application"] i dont know why it runs ok in docker but not in the web. I'd appreciate … -
Form filtering in Django?
error: 'RegisterlesonForm' object has no attribute 'id' form class RegisterlesonForm(forms.ModelForm): class Meta: model = Registerleson fields = ['leson', 'book', 'discount'] widgets = { 'leson': forms.Select(attrs={'class': 'form-control'}), 'discount': forms.NumberInput(attrs={'class': 'form-control'}), 'book': forms.Select(attrs={'class': 'form-control'}), } def __init__(self, *args, **kwargs): super(RegisterlesonForm, self).__init__(*args, **kwargs) self.fields['leson'].queryset = Registerleson.objects.raw( "SELECT * FROM classes_classes WHERE classes_classes.id not IN (SELECT leson_id FROM member_registerleson WHERE student_id = %s )", {self.id}) -
how can i code a plagiarism detector using python django [closed]
I want to make a website where a web URL given by the user is compared with the text entered by the user and the copy rates are printed on the screen. how can i code this with django? i used jaccard similarity to find the plagiarism ratio but I don't know how to ask the user to enter a text and whether that text has been copied from a website. My goal is to make a simple version of turnitin. -
Select using Django/Ajax
In the user profile page, there is a section for user to see the comments made on their posts. There is also a Select filter to query comments by Post. I am trying to use AJAX with the goal of avoiding page reload/refresh. Where am I going wrong? Since the page is still refreshing, I think I am missing some sort of div wrapper around my results. Besides that, the script probably needs more details. The /api url is showing the objects in Json format if I visit the link. urls.py: path('api/',views.api,name='api'), path('profile/<str:pk>/', views.profile, name='profile') views.py def profile(request,pk): user = request.user posts = Post.objects.filter(active=True, owner=request.user) notfirstvisit = UserFirstVisit.objects.filter(user=request.user) comments = Comment.objects.filter(post_owner=request.user) filter_post = request.GET.get('filter_post', None) if filter_post: comments = comments.filter(post__id__exact=filter_post) return render(request, 'profile.html', {'user':user, 'notfirstvisit':notfirstvisit, 'posts':posts, 'comments':comments}) profile.html: <form id="filter_post_form"> <select class="form-select" id="filter_post" name='filter_post'> <option value=""{% if value == "" %}selected {% endif %}>Select Post</option> {% for post in posts %} <option value="{{post.id}}" {% if post.id == filter_post %} selected="selected" {% endif %}> {{post.title}} - {{post.created}} </option> {% endfor %} </select> <br> <button name="filter" id="filter" class="btn btn-primary" type="submit">Apply Filter</button> <button name="clear" id="clear" class="btn btn-primary">Clear Filter</button> <br> </form> <div style="overflow-y:auto;max-height: 500px;"> {% for comment in comments %} <div class="card container py-1"> … -
How do you embed a webpack ReactJs bundle file in Django templates html file?
I used webpackJs to generated a dist folder with an index.html and bundle.js. I then copied the bundle.js into my Django project, used django template language to embed the bundle.js into a django index.html file containing a root div. When the browser downloads the index.html and bundle.js files at the root localhost/index, only Django Site with ReactJs appears. I dont understand, how are you suppose to run ReactJs in production? index.html file serving ReactJs Bundle from Webpack The bundle.Js is located in a static folder in the Django application <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Index</title> {% load static %} <script src="{% static '/Core_CRUD/bundle.js' %}" type="text/javascript"></script> </head> <body> <h1>Django Site with ReactJs</h1> <div id="root"></div> </body> </html> Tried debugging, didnt work -
Django admin page - open 'VIEW SITE' in a new tab?
In admin portal of my Django app (v. 3.1), is it possible to configure the "VIEW SITE" link in the site header so that it will open in a new tab, target="blank"? I'm referring here to the link whose href can be configured via admin.site.site_url... I'd like to give my admin users quick and easy access to the site linked there, but I don't want them to be navigating away from their authenticated admin session. I currently have this value set to a custom configuration in urls.py like so protocol = 'https' domain = 'mysite.com' if os.environ.get('DJANGO_DEVELOPMENT'): protocol = 'http' domain = 'localhost:8080' admin.site.site_url = f'{protocol}://{domain}' as this URL actually needs to point at an application running on a different server. -
Is there a way to make a Form table that submits all the values?
In my django project, I have the following code that ideally the user to could edit modify an then submit, sending the all of the values to my views.py via forms.py (or any other possible way) so I can perform some calculations on the values. I have only gotten the code to work when it sends one value that has been changed then submitted but I need all of the values in the table. Any suggestions on how to do this would be greatly appreciated. function edit(element) { var tr = jQuery(element).parent().parent(); if (!tr.hasClass("editing")) { tr.addClass("editing"); tr.find("DIV.td").each(function() { if (!jQuery(this).hasClass("action")) { var value = jQuery(this).text(); jQuery(this).text(""); jQuery(this).append('<input type="text" value="' + value + '" />'); } else { jQuery(this).find("BUTTON").text("save"); } }); } else { tr.removeClass("editing"); tr.find("DIV.td").each(function() { if (!jQuery(this).hasClass("action")) { var value = jQuery(this).find("INPUT").val(); jQuery(this).text(value); jQuery(this).find("INPUT").remove(); } else { jQuery(this).find("BUTTON").text("edit"); } }); } } .table { display: table; border-collapse: separate; border-spacing: 2px; } .thead { display: table-header-group; color: white; font-weight: bold; background-color: grey; } .tbody { display: table-row-group; } .tr { display: table-row; } .td { display: table-cell; border: 1px solid black; padding: 1px; } .tr.editing .td INPUT { width: 100px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <div class="thead"> <div class="tr"> <div class="td">Column … -
Assign registered User to Customer Model
I want to assign a new registered User to my customer model. At the moment user is successfully registered into the back end but is not assigning to a new Customer model, When redirected to home page after registration the following error occurs: Exception Value: User has no customer. The error is pointing to this utils model: def cartData(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, order_status='P') items = order.orderitem_set.all() cartItems = order.get_cart_items else: cookieData = cookieCart(request) cartItems = cookieData['cartItems'] order = cookieData['order'] items = cookieData['items'] return {'cartItems': cartItems, 'order': order, 'items': items} Customer Model: class Customer(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, null=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=255) birth_date = models.DateField(null=True) User Register and Login Views: def UserRegister(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) messages.success(request, ("Registration successful, you are now logged in...")) return redirect('home') else: form = UserRegisterForm() return render(request, 'authenticate/register.html', {'form': form}) def UserLogin(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request, ("You were successfully logged in...")) return redirect('home') …