Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Linux python django site-packages not recognized in envelope
I have tried to create envelope on my linux pop os system using miniconda. When I activate it, I can install packages using pip, but when I run my django instance it doesn't find the modules. If I type which python is shows the miniconda path correctly. I can look in the site-packages folder and see the packages installed. I've tried installing django-anymail and corsheaders and they are both not being found. It does find my locally installed apps. If I use the command line and open python and then import, it does not recognize my modules installed in the virtual envelope either. I thought it was a problem with conda, so I also created an envelope using python's native method: python3 -m venv I have the same problem with it finding pip install site-packages. Is there a command I can run to show all available packages? -
Model-wide validation for a Field type in Django ie., validate that all DecimalField of a model is greater than 0
I have three Decimal fields that all have the same validator: ` class MyModel(models.Model): one = models.DecimalField(validators=[great_than_zero]) two = models.DecimalField(validators=[great_than_zero] three = models.DecimalField(validators=[great_than_zero] ` Is there a pythonic way to enforce this validator for the entire model, so that no Decimal Field can have a negative number. If I know that all of my Decimal fields will be positive, it would be nice to not right the same piece of code for each one. -
cursor.fetchone() returns None when it shouldn't
So basically, I wanted to use an sqlite3 database to store data in my django project. Unfortunately, this view returns None for some reason. Code: def req_count(request): db = sqlite3.connect(db_path) cursor = db.cursor() cursor.execute("SELECT * FROM reqcount_data") db.commit() reqs = cursor.fetchone() db.commit() return HttpResponse(reqs) Also please tell me where a db.commit() is redundant. NOTES: I am using Windows 10 I am using Python 3.8 I am using Django 3.2.6 -
What did my teacher mean by 'db.sqlite3' will fall short in bigger real word problems?
I am very new to programming and this site too... An online course that I follow told me that it is not possible to manage bigger databases with db.sqlite3, what does it mean anyway? -
How to post a file to Django/DRF using python requests
I have the following code to post a json dataset/file to a Django/DRF API db. I get the error message '{"ohlc":["No file was submitted."]}' what am I doing wrong ? test_url = "http://localhost:8000/stocks/aapl/price/" test_file = { "aapl": open("./ohlc_aapl.json", "rb") } payload = x.to_dict(orient='records') r = requests.post(test_url, files=test_file, json=payload) -
database error after Heroku deployment for django app
I made a simple API using the Django REST framework and consumed the API with ajax. This is my first time using Heroku, after I deployed the project it tries to save the data to a relation called "api_task" which causes an error. I have debug on True and this error shows when I try to add a new task to my todo app: relation "api_task" does not exist LINE 1: INSERT INTO "api_task" ("title", "completed") VALUES ('new t... this is my model class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.title ajax call for creating and updating new tasks let method = 'POST'; let url = 'http://127.0.0.1:8000/api/task-create/'; if (activeItem){ method = 'PUT'; url = `http://127.0.0.1:8000/api/task-update/${activeItem.id}/`; activeItem = null; } const title = document.getElementById("title").value fetch(url, { method:method, headers:{ 'Content-Type': 'application/json', 'x-CSRFToken': csrfToken }, body:JSON.stringify({'title':title}) }) .then(response =>{ buildList() document.getElementById('form').reset() }) -
Django - add required auto-generated `uuid4` to existing project
I'm trying to add internal_code to a Django Model in the existing project. internal_code = models.CharField(max_length=128, default=uuid.uuid4, unique=True) The problem is that when running migrate, Django raises IntegrityError: DETAIL: Key (internal_code)=(b24f1ca6-bd90-4c91-87b0-5f246a4057e1) is duplicated. I understand that this problem exists only during migrate as it is generated just once. Is there a way to avoid this behavior without having to do this?: set field to null=True migrate add RunPython that will populate all the existing objects internal_code fields set field to null=False -
¿Por que al crear un projecto nuevo de django en visual studio 2019, se crea con la vesion 2.1.2 y no la mas actual?
Tengo instalado django 3.2.6, pero al crear el proyecto desde la opcion que da visual estudio, se crea con la version 2.1.2 Django settings for DjangoWebProject4 project. Based on 'django-admin startproject' using Django 2.1.2. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ -
Django condition in save method
I got storage places wich have the field amount and article. If i call save() on one place i want to set the article field to None. Whats is the best approach for this ? I already tried this: def save(self, *args, **kwargs): if self.amount == 0: self.article = None super(LagerPlace, self).save(*args, **kwargs) -
Page Not Found 404 Django & Python
I am having the following error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in Decoder.urls, Django tried these URL patterns, in this order: form.html [name='form1'] hl7 [name='hl7'] The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Its my first time writing code using Django `from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('hl7rest.urls')), ]` and this other file from . import views from django.urls import path urlpatterns = [ path('form.html', views.render_form_View, name='form1'), path('hl7', views.hl7_web_view ,name='hl7'), ] -
Render template tags when passing as variable in django
I want to pass some html as a string in a variable to a template, which also includes a link: <a href= {%url: 'app:page'%}> If I pass the variable though, the template tags are not invoked. If I use {{variable | safe}} to escape the restrictions, still it is not being called. I think I have a major error in my thinking, or is it just not possible to do this? -
On click, the button checks checkbox in another html
I tried to follow this example; Set to true state a checkbox in a different page(javascript) but can't get it to work, not sure how to fix it? Getting error message; Request Method: GET Request URL: http://localhost:8000/profileusers/register.html?chk=1" First Page - terms.html <div class="row"> <a href="{% url 'register' %}" target="_blank"> <input type="button" name="acceptButton" class="btn accept-button" value="Accept" id="acceptButton" onclick="registerCheck(this.id)"> </a> <a href="{% url 'register' %}"> <input type="button" name="declineButton" id="declineButton" class="btn decline-button" value="Decline"> </a> </div> <script> function registerCheck(clicked_id) { if (clicked_id === 'acceptButton') { window.location.href = "register.html?chk=1"; } } </script> Second Page - register.html <div class="form-check"> <input class="form-check-input" type="checkbox" id="terms-box" name="terms-box"> <label class="form-check-label" for="flexCheckDefault"> &nbsp; <a href="{% url 'terms' %}" class="link-terms">Terms & Conditions</a> </label> </div> <script> var url = window.location.href.split("?"); if (url[1].toLowerCase().includes("chk=1")) { $('#terms-box').attr('checked', true); } </script> -
Ajax with Django creates duplicate content
I had asked a previous question, but the answer was not sufficient. I am trying to render graphs in a Django template using change of a dropdown using Ajax. But this creates duplicate content in the UI. I am not sure why this is happening. Here is my code Django view def home(request): if request.method=='POST': year = request.POST['year'] df, cus_dict = generate_df(year) year_choro = createStormDataGraph(year, cus_dict) context = {'graph': year_choro, 'year': year} return render(request, 'index.html', context=context) default1 = default() context = {'default': default1} return render(request, 'index.html', context=context) def ajax(request): return render(request, 'ajax.html') home template <form action="{% url 'home' %}" method='post' class='center' id='year-form'> {% csrf_token %} <div class="line-break"></div> <select class="form-select form-select-lg mb-3 dropdown-btn" aria-label="Default select example" name="year" id='dropdown-btn'> <option value="none" selected disabled hidden> Select a year </option> <option value="2017">2017</option> <option value="2018">2018</option> <option value="2019">2019</option> <option value="2020">2020</option> </select> </form> <div id="message"></div> <div class="graph center" id='graph'> </div> ajax template <body> {% if graph %} {{ graph.0|safe }} {% else %} no graph was provided {% endif %} </body> javascript <script type="text/javascript"> $('#dropdown-btn').on('change', function () { var frm = $('#year-form'); $.ajax({ type: frm.attr('method'), url: "{% url 'home' %}", data: frm.serialize(), success: function (data) { console.log('success') $(graph).html(data) }, error: function (data) { $("#message").html("Something went wrong!"); } … -
Cant get data from view to django template
Problem as in title. I can not get data from view to template I get <QuerySet [{'id': 3, 'order_user_id': 13, 'ordered': False, 'total': Decimal('0.00')}]> when i use {{ order }}. I would like to get OrderedItems and Total from Order Model. How can i do that? views.py def cart(request): order = Order.objects.values() context = {'order': order} return render(request, 'shop/cart.html', context) models.py: class OrderItem(models.Model): order_item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Order(models.Model): order_user = models.OneToOneField(User, on_delete=CASCADE) order_items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) total = models.DecimalField(default=0.00, decimal_places=2, max_digits=11) class Item(models.Model): title = models.CharField(max_length=150) price = MoneyField( decimal_places=2, default=0, default_currency='USD', max_digits=11, ) cart.html {% extends 'shop/base.html' %} {% block content %} <div class="container"> {% include 'shop/navbar.html' %} <div> {{order}} {{order.total}} </div> </div> {% endblock content %} -
nm, address = addr ValueError: not enough values to unpack (expected 2, got 1), Django Rest Framework
I am working on a personal project that is an E-Commerce made with Django Rest Framework and Vue.js. I have created a contact form and when I try sending it, it creates an error: /venv/lib/python3.9/site-packages/django/core/mail/message.py", line 96, in sanitize_address nm, address = addr ValueError: not enough values to unpack (expected 2, got 1) It seems like it needs some kind of additional value that it doesn't get from my views.py. This is my Serializer: from rest_framework import serializers from .models import Contact class ContactForm(serializers.ModelSerializer): class Meta: model = Contact fields = ( 'first_name', 'last_name', 'phone', 'email', 'subject', 'message', ) This is my Views.py: from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from django.core.mail import send_mail from django.template.loader import render_to_string from .models import Contact from .serializers import ContactForm @api_view(['POST']) def contact_form_post(request): if request.method == "POST": serializer = ContactForm(data=request.data) if serializer.is_valid(): first_name = serializer.validated_data['first_name'], last_name = serializer.validated_data['last_name'], phone = serializer.validated_data['phone'], email = serializer.validated_data['email'], subject = serializer.validated_data['subject'], message = serializer.validated_data['message'] print(first_name, last_name, phone, email, subject, message) context = { 'first_name': first_name, 'last_name': last_name, 'phone': phone, 'email': email, 'subject': subject, 'message': message } send_mail( subject, render_to_string('emails/contact.txt', context), email, ['emailThatItryToUse@gmail.com'], fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None ) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return … -
browser is adding strong tag before and after the div tag automatic
I have a website sauravportfolio.pythonanywhere.com . It was running good earliar. But after some time a strong tag is adding before and after the div tag. before error it was looking like this after error it is looking like this The error is here which is marked by a red circle i can't able to find why this strong tag is here while this is not present in my code. Please help me to find this error. Why this is happening so. And how can i overcome on this situation. -
Why does INSTALLED_APPS in Django settings stops seeing directories if you rename settings.py file?
I work in Pycharm 2019.3.3. So if the settings.py file wasn't renamed, when you start typing a name of a directory inside INSTALLED_APPS, Pycharm indexes what you can choose from. But if you rename the file to something else (common.py eg), it doesn't. But the whole thing works and an app gets included anyway. How can I make it index properly? Same thing happens if you put the settings.py file inside a project/project/settings/ directory (instead of the default project/project). What actions should be taken to make it work as intended? -
Issue on Entity Relation
I need a helping hand in the area of Entity Relation. In this particular project, a student in a class (i.e J.S.S 1) should be able to attend examination for J.S.S 1 in a particular term and academic session. Note: In my country we have "Academic session, in academic session we have terms, in a term we have 1st, 2nd and 3rd term. Student should be a able to select field for class, subject ,academic session & term and print result for each term and session. Here is the admin model: from django.db import models from django.conf import settings class Course(models.Model): course=models.CharField(max_length=150,unique=True) def __str__(self): return self.course class Paper(models.Model): paper=models.CharField(max_length=150) def __str__(self): return self.paper class Questions(models.Model): qs_no=models.IntegerField() course=models.ForeignKey(Course,on_delete=models.CASCADE) paper=models.ForeignKey(Paper,on_delete=models.CASCADE) questions=models.TextField() answers=models.CharField(max_length=20) option_a=models.TextField() option_b=models.TextField() option_c=models.TextField() option_d=models.TextField() def __str__(self): return str(self.qs_no)+self.questions class Answer(models.Model): student=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) question=models.ForeignKey(Questions,on_delete=models.CASCADE) answer=models.CharField(max_length=20) date=models.DateTimeField(auto_now_add=True) def __str__(self): return self.answer Here is the account model: from django.db import models from admin_dash.models import Course from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser) class UserManager(BaseUserManager): def create_user(self, phone, roll, course, password, name=None): if isinstance(course, int): course = Course.objects.get(pk=course) user = self.model(phone=phone, roll=roll, course=course, name=name) user.set_password(password) user.save() return user def create_superuser(self, phone, roll, course, password, name=None): user = self.create_user(phone=phone, roll=roll, course=course, password=password, name=name) user.is_staff = True user.is_admin = … -
Django models inheritance
I want to create base model for my submodels, for example: Car(Base) and Truck, Sportcart etc. And I want to bind them all using base class with another class, cuz I don't want to bind all of them separately with another class. Example: I have a user and I want to add to him cars (I will do it separately for each class, yes). And I want to get all of them using my base Car class. -
After installing Django with poetry it says "No module named django" in active venv
I'm playing with poetry because I'm thinking about switching from pip. Following the basic usage examples, I'm doing the following: $ poetry new poetry-demo $ cd poetry-demo $ poetry add django $ django-admin #can't find it $ poetry shell #or poetry $(poetry env info --path)/bin/activate $ django-admin Traceback (most recent call last): File "/Users/cjones/Library/Caches/pypoetry/virtualenvs/poetry-demo-Jq168aNm-py3.8/bin/django-admin", line 5, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' Also tried in this order: $ poetry new poetry-demo $ cd poetry-demo $ poetry shell #or poetry $(poetry env info --path)/bin/activate $ poetry add django $ django-admin Traceback (most recent call last): File "/Users/cjones/Library/Caches/pypoetry/virtualenvs/poetry-demo-Jq168aNm-py3.8/bin/django-admin", line 5, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' Check the pyproject.toml: [tool.poetry] name = "poetry-demo" version = "0.1.0" description = "" authors = ["Your Name <you@example.com>"] [tool.poetry.dependencies] python = "^3.8" Django = "^3.2.6" [tool.poetry.dev-dependencies] pytest = "^5.2" [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" Check poetry show: asgiref 3.4.1 ASGI specs, helper code, and adapters attrs 21.2.0 Classes Without Boilerplate django 3.2.6 A high-level Python Web framework that encourages rapid development and clean, pragmatic design. more-itertools 8.8.0 More routines for operating on iterables, beyond itertools packaging 21.0 Core utilities for Python packages pluggy 0.13.1 … -
Django rest with formset
Right now I have a working formset page, create one record in ModelA and 3 records for ModelB using foreignkey. Now I would like to create restApi for that, for now I have linked one model to another but my question is how to make ModelB add a few times for this model. serializers.py class DailyMontageCreateSerializer(serializers.ModelSerializer): class MonterDailyTempSerializer(serializers.ModelSerializer): class Meta: model = models.MonterDaily exclude = ['daily_montage', 'created', 'updated'] validators = [ UniqueTogetherValidator( queryset=models.MonterDaily.objects.all(), fields=['name', 'date'] ) ] daily_montage = MonterDailyTempSerializer() class Meta: model = models.DailyMontage exclude = ['created', 'updated'] validators = [ UniqueTogetherValidator( queryset=models.DailyMontage.objects.all(), fields=['team', 'date'] ) ] def create(self, validated_data): model_b_data = validated_data.pop('daily_montage') model_a_instance = models.DailyMontage.objects.create(**validated_data) models.MonterDaily.objects.create(daily_montage=model_a_instance, **model_b_data) return model_a_instance views.py class DailyMontageCreateAPIView(generics.CreateAPIView): queryset = models.MonterDaily.objects.all() serializer_class = serializers.DailyMontageCreateSerializer now if i will add like that is good { "daily_montage": { "status": null, "name": 1 }, "type": null, "date": null, "user": 1, } but i want to be like that { "daily_montage": { "status": null, "name": 1 }, "daily_montage": { "status": null, "name": 2 }, "daily_montage": { "status": null, "name": 3 }, "type": null, "date": null, "user": 1, } -
Return Specific User in Django
Still pretty new with Django and trying to work out how to display current user's profile when clicking 'view profile' through the nav-bar and the specific user when clicking 'view profile' on someone else's project page. Currently, when clicking on the nav-bar, it correctly returns the current user's profile, however, when clicking to see someone else's page on the project detail page, it still returns current user and not the desired user's profile page. I still want the url to show up like so: 'accounts/username/view_profile' and not 'accounts/pk/view_profile' I've tried to the 'get_context_data' method in my ViewProfileView but it returns an error about calling the url with slugs or object pk. models.py I think I have the slug properly set up but I'm not sure how to implement it or if that will even solve my problem here - I've tried adding the slug to the url-conf and passing it through the get_context_data in views.py but I could never get it to work properly, just error after error. ... class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) slug = models.SlugField(blank=True, db_index=True, unique=True) about = models.TextField(max_length=500, null=True, blank=True) profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile") facebook_url = models.CharField(max_length=255, null=True, blank=True) twitter_url = models.CharField(max_length=255, null=True, … -
An error occurred (403) when calling the HeadBucket operation: Forbidden
After a refactoring on an AdminModel class this error is happening in some instances. -
Django: how to filter queryset by the combination of related objects fields?
I have three related models that look like this: class Library(models.Model): name = models.CharField(max_length=200, blank=False) class Meta: verbose_name = 'library' verbose_name_plural = 'libraries' class Section(models.Model): name = models.CharField(max_length=200, blank=False) library = models.ForeignField(Library, related_name='sections', on_delete=models.CASCADE, null=False) class Meta: verbose_name = 'section' verbose_name_plural = 'sections' class Book(models.Model): title = models.CharField(max_length=200, blank=False) section = models.ForeignField(Section, related_name='books', on_delete=models.CASCADE, null=False) is_available = models.BooleanField(default=True) class Meta: verbose_name = 'book' verbose_name_plural = 'books' And say I need to filter all the libraries that have available books with title "The Lord of the Rings". If I create a request like this queryset = Library.objects.filter(sections__books__title="The Lord of the Rings", sections__books__is_available=True).distinct() it will include libraries that have my book and it's not available, because the filter condition doesn't apply to the same book. How do I specify that I need both filters to combine for related objects? -
Direct assignment to the forward side of a many-to-many set is prohibited. Using set makes another error
I am trying to make cart at my e-commerce page, full in django. But I have a problem. Code below after post request occurs an error - Direct assignment to the forward side of a many-to-many set is prohibited. Use order_items.set() instead.When i use set() then i get error object is not iterable. What should I do? def post(self, request, pk): if 'buy' in request.POST: item = get_object_or_404(Item, id=pk) orderItem, created = OrderItem.objects.get_or_create(order_item=item) order, created = Order.objects.get_or_create(order_user=request.user, order_items=orderItem) order.save() HttpResponse('Items added to the database') models.py class OrderItem(models.Model): order_item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Order(models.Model): order_user = models.ForeignKey(User, on_delete=CASCADE) order_items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) total = models.DecimalField(default=0.00, decimal_places=2, max_digits=11)