Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass persistent volume to postgres docker
I want to run PostgreSql database with docker, I created a docker-compose like below: django: restart: always build: . ports: - "8000:8000" depends_on: - pgdb #environment: # - url=https://api.backend.example.com #command: "gunicorn config.wsgi:application --bind 0.0.0.0:8000" #networks: # - bridge pgdb: image: postgres container_name: pgdb environment: - POSTGRES_DB=hbys_filyos - POSTGRES_USER=healmedy - POSTGRES_PASSWORD=mhacare1 I want to run PostgreSql database with docker, I created a docker-compose like below: After building I run docker run -p 80:8000 surgery4:dev & as follows. I am getting the following error in terminal: django.db.utils.OperationalError: could not translate host name "pgdb" to address: Try again -
styles.css file is not working. how to solve the problem?
I made a website and got to the point where you need to connect styles.css, but after all the manipulations, my site has not changed and no design has been connected. I tried to rewrite css and html, tried different tips, but nothing helped me. any ideas? I would be grateful for any advice! 1part base.html <!DOCTYPE html> <html lang="en"> <head> <title>{{title}}</title> <link type="text/css" href="{% static 'women/css/styles.css' %}" rel="stylesheet" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="shortcut icon" href="{% static 'women/images/main.ico' %}" type="image/x-icon"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <table class="table-page" border=0 cellpadding="0" cellspacing="0"> <tr><td valign=top> {% block mainmenu %} <div class="header"> <ul id="mainmenu" class="mainmenu"> <li class="logo"><a href="#"><div class="logo"></div></a></li> {% for m in menu %} {% if not forloop.last %} <li><a href="#">{{m.title}}</a></li> {% else %} <li class="last"><a href="#">{{m.title}}</a></li> {% endif %} {% endfor %} </ul> <div class="clear"></div> </div> {% endblock mainmenu %}``` I've added screenshots below if anyone needs them. [1][1] [2][2] [3][3] [4][4] - PS I have already tried these options, gives an error ```<link type="text/css" href="{% static 'women/css/styles.css' %}" rel="stylesheet" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="shortcut icon" href="{% static 'women/images/main.ico' %}" type="image/x-icon"/> <meta name="viewport" content="width=device-width, initial-scale=1.0">``` [1]: https://i.stack.imgur.com/3exw2.png [2]: https://i.stack.imgur.com/ye5k7.png [3]: https://i.stack.imgur.com/ZKSs6.png [4]: https://i.stack.imgur.com/eQRvd.png -
Ubuntu terminal opens as root user and forgot "code ." how to fix? picture included
Ubuntu crashed when I had the shell open for a django server. When it rebooted and everytime since, it opens me as the root user. How do I change it back to open me as user? Second, I can find my way back to the user via su username(I found this command via stack overflow). But it seems to have forgotten everything I set up. Like it no longer knows the command "code ." for VS code Any idea on how this happened and what I should do to fix it. See picture below -
Django copy object: func with self.id in html, urls and views
I try copy my object. I can receive copy from my "def checklist_copy" if i explicitly specify pk.(example) But, i try work with 'self.pk' and this is not work. I want to copy the object under which I click on the button i used different variations: (pk=pk) in function, checklist.id and checklist.pk in html template, tried passing "self" to function and doing self.pk doing pk=int(Checklist.object.get.id()) to then transfer this "pk" to (pk=pk) in object.id() try include func in class DetailView did not achieve a result Please help. I don't know where and what to look for Example: models.py from django.urls import reverse from django.db import models class Checklist(models.Model): title = models.CharField(max_length=250) def get_absolute_url(self): return reverse ('checklist:checklist', kwargs={'id': self.id, 'title': self.title}) def __str__(self): return self.title view.py from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Checklist from django.shortcuts import redirect from django.urls import reverse_lazy class CheckListView(ListView): model = Checklist context_object_name = 'checklists' class CheckListDetail(DetailView): model = Checklist context_object_name = 'checkList' template_name = 'base/checklist.html' def checklist_copy(request): dest = Checklist.objects.get(pk=2) #here i need to use self.id(pk), but can't include 'self' in args of func dest.pk = None dest.save() return redirect(reverse_lazy('checklists')) urls.py (my app) from django.urls import path from .views import CheckListView, … -
Django authentication when database is changed
I have created a Django application with authentication using django.contrib.auth. I was using a database with user admin and password xyz everything works fine. Then I changed the database which has user admin with password abc. The issue is my application is running fine after refresh (logged in as admin) even though I didn't know the password abc. which shouldn't be possible. After I logged out, everything is working fine as expected. -
Django upload file size limit and restriction
I have a form in my app where users can upload files so how can i set a limit to the uploaded file size and type ? **models.py** class Document(models.Model): emp = models.ForeignKey(Emp, null=True, on_delete=models.SET_NULL) Description = models.CharField(max_length=100, null=True) Fichier = models.FileField(upload_to='file/') data_created = models.DateTimeField(auto_now_add=True, null=True) **forms.py** class documentForm(ModelForm): class Meta: model = Document fields = '__all__' exclude = [] **view.py** def createDocument(request): forms = documentForm() if request.method == 'POST': forms = documentForm(request.POST, request.FILES) if forms.is_valid(): forms.save() return redirect('/') context = {'forms':forms} return render(request, 'accounts/document_form.html', context) -
Web socket disconnecting after stablishing a connection
I got a web socket connection that I perform with django channels, my app works perfectly fine in local, but when trying to run it on the vps, the web socket gets disconnected right after stablishing a connection with a 1005 code const socket = new WebSocket('wss://mydomain.com/ws/chat/testing/'); I was sending a message to the backend in socket.onopen() function, but that was not the problem since after commenting that line of code, the connection gets also closed The nginx configuration file looks like this: location /ws/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Url-Scheme $scheme; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_pass http://127.0.0.1:8115; } Django routing.py: application = ProtocolTypeRouter({ 'websocket':AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ path('chat/testing/', Chat().as_asgi()) ]) ) ) }) Setting.py: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } I don't know if relevant but when using const socket = new WebSocket('wss://mydomain.com:8115/ws/chat/testing/'); I got a connection failed with code 1006 -
try block is working but except block is not handling error in python
While Handling Python dictionary key error except block is not working but try block is working. Below is my code def catch_empty_key(a): try: return 'aaaa' except : return 'bbbb' def zohoapicall(accesstoken): accesstoken = "" if accesstoken == "": parameters = { "refresh_token":"1000.06f10f49d6f00478887e3820634b928f.c045ff2a9dcb9c99057ec42645bf1e44", "client_id":"1000.UKZQIWVQ2A2THKSZ2126Y7E7CAA8CW", "client_secret":"91d25fbaeea0e81190a681708cd554a1030a9c4547", "redirect_uri":"https://www.google.com", "grant_type":"refresh_token", } response = requests.post("https://accounts.zoho.com/oauth/v2/token?", params=parameters) if response.status_code == 200: data = response.json() accesstoken = data['access_token'] headers = { 'Content-Type':'application/json', 'Authorization':'Zoho-oauthtoken ' + str(accesstoken) } response = requests.get("https://books.zoho.com/api/v3/invoices", headers=headers) if response.status_code == 200: data1 = response.json() data_2=[catch_empty_key(invoice['not_a_key']) for invoice in data1['invoices']] return HttpResponse(data_2, accesstoken) Here in the second last line data_2=[catch_empty_key(invoice['not_a_key']) for invoice in data1['invoices']] except block of catch_empty_key function is not working and it is throwing an error. On the Other hand if I replace second last line with something that is a key of invoice then try block is working and returning aaa as output. for example data_2=[catch_empty_key(invoice['is_a_key']) for invoice in data1['invoices']] I want to understand why this error is coming and how can we solve it? -
Authentication returns None in django rest frame work API
views.py @api_view(['POST']) def login(request): data = {} email = request.data.get('email') password = request.data.get('password') user = authenticate(email = email, password = password) U = User.objects.get(email=email) if user is not None: login(request, user) data['response'] = 'successfully logged in' elif Userprofile.objects.filter(email=email).exists() == False: data['response'] = 'user does not exist' elif U.is_active == False: data['response'] = 'Please verify your email' else: data['response'] = 'invalid password' return JsonResponse(data) otp=random.randint(11111,99999) @api_view(['POST']) def signup(request): serializer = UserprofileSerializer(data=request.data) data = {} if serializer.is_valid(): name = serializer.validated_data['name'] email = serializer.validated_data['email'] phone_number = serializer.validated_data['phone_number'] password = make_password(serializer.validated_data.get('password')) account = Userprofile.objects.create_user(name = name, email = email, phone_number = phone_number, password = password) data['response'] = 'successfully registered a new user' send_mail( 'Welcome to Trycompound', 'Your OTP is '+str(otp), EMAIL_HOST_USER, [email], ) user = User.objects.get(email=email) user.otp = otp user.save() else: data = serializer.errors return JsonResponse(data) I really can'f figure what's wrong because I have actually done these with the normal templates and when i tried it with the django rest framework, I am unable to login because authenticate is returning 'None'. and yes User is active, it says 1 in the database. -
issues with Docker on wsl (ubuntu 22.04)
An attempt to build a docker image fails on RUN pip install -r requirements.txt step with the following error: WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ for some reason, asgiref==3.5.2 doesn't want to install. What could be the reason for this? System used: OS: Windows 11 WSL 2 with Ubuntu 22.04 on board Docker version 20.10.19, build d85ef84 Dockerfile contents: # Pull base image FROM python:3.10.6-slim-bullseye # Set enviroment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . requirements.txt contents: asgiref==3.5.2 Django==4.1.2 sqlparse==0.4.3 -
how to get foreignkey names instead of sql reference number django view
Im trying to build a simple rest api in django. i have a transaction, account and stock table. Each transaction points to 1 account and 1 stock(on seperate tables using foreign keys). im trying to have my api gets the stock ticker for each transaction and not the sql reference number. does anyone know how to get simple views to return values instead of table keys? the serializers im using: class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = "__all__" class StockSerializer(serializers.ModelSerializer): class Meta: model = Stock fields = "__all__" class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = "__all__" the models for transaction and stock: class Stock(models.Model): ticker = models.CharField(max_length=10, unique=True) name = models.CharField(max_length=200) price = models.FloatField() def __str__(self): return self.ticker class Transaction(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) stock = models.ForeignKey(Stock, on_delete=models.CASCADE) amount = models.IntegerField() price = models.FloatField() type = models.CharField(max_length=10) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.account im leaving out the account/user model but its a mess and half tied into the django base user model the view im using is a basic APIVIEW: class TransactionView(APIView): permission_classes = (IsAuthenticated,) authentication_classes = (JWTAuthentication,) def get(self, request, *args, **kwargs): account = Account.objects.get(email=request.user.email) transactions = Transaction.objects.filter(account=account) serializer = TransactionSerializer(transactions, many=True) return Response(serializer.data) … -
Relative links to admin.py
There is a class in admin.py: class NewsAdmin(TranslationAdmin): form = NewsForm list_display = ('title', 'date' 'show_url') def show_url(self, obj): return format_html("<a href='http://www.host.ru/news/{url}' target='_blank'>view</a>", url=obj.id) show_url.short_description = "View" Need a link http://www.host.ru replace with a relative one, something like this: protocol + domain name + news/{url} How can this be done? -
ModelChoiceFIeld Usage and what to include in queryset?
I cannot seem to figure out why my ModelChoiceField is not working, even after going through the django documentation about ModelForm which confused me despite having successfully relied on them throughout my learning. The error in my code is probably silly, and I apologize for that in advance. The error I get on my terminal when trying to makemigrations is: 'line 429, in getattr raise AttributeError(name) from None AttributeError: objects' forms.py from random import choices from django import forms from .models import Student from students.choices import * class StudentForm(forms.ModelForm): class Meta: model = Student fields = '__all__' #imports all of Student model's fields labels = { 'student_number': 'Student Number', #changes how the attribute names are presented to the user 'first_name': 'First Name', 'last_name': 'Last Name', 'email': 'Email', 'english': 'English', 'math': 'Math', 'language': 'Language', 'science': 'Science', 'ib_predicted': 'Predicted IB Score' } widgets = { 'student_number': forms.NumberInput(attrs={'class': 'form-control'}), 'first_name': forms.TextInput(attrs={'class': 'form-control'}), 'last_name': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'english': forms.ModelChoiceField(queryset=English.choices), 'science': forms.ModelChoiceField(queryset=Science.objects.all()), 'language': forms.ModelChoiceField(queryset=Language.objects.all()), 'math': forms.ModelChoiceField(queryset=Math.objects.all()), 'ib_predicted': forms.NumberInput(attrs={'class': 'form-control'}) } choices.py from unittest.util import _MAX_LENGTH from django.db import models from django.utils.translation import gettext_lazy as _ class English(models.TextChoices): LANGLIT = 'LL', _('Language and literature') LIT = 'L', _('Literature') class Math(models.TextChoices): AA = 'AA', _('Analysis … -
Django Rest Framework Serializer PrimaryKeyRelatedField pass in uuid list
So, I am trying to make a social media application and users can tag other users in their post. class Post(models.Model): author = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) caption = models.CharField(max_length=100, null=True, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) date_created = models.DateTimeField(auto_now_add=True) date_edited = models.DateTimeField(auto_now=True) allow_comments = models.BooleanField(default=True) archived = models.BooleanField(default=False) media_file_url = models.FileField(upload_to='videos/', validators=[validate_file_extension]) tags = TaggableManager(blank=True, through=TaggedHashtag) mentioned_users = models.ManyToManyField(User, blank=True, through='MentionedUser') class MentionedUser(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) date_created = models.DateTimeField(auto_now_add=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) tagged_user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: unique_together = (('post', 'tagged_user')) ordering = ['date_created'] For serializing the uuids for the mentioned_users, I followed these instructions. Everything works fine, I can submit one uuid correctly like this: But when I try to submit more than one uuids, I get this error: Here is my serializer: class PostSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField() mentioned_users = serializers.PrimaryKeyRelatedField(many=True, allow_null=True, queryset=User.objects.all(), pk_field=serializers.UUIDField(format='hex')) id = serializers.CharField(read_only=True) class Meta: model = Post fields = [ 'caption', 'allow_comments', 'media_file_url', 'id', 'tags', 'mentioned_users', ] What am I doing wrong here? What is the correct way to submit list of uuids? Also, is the present method I am using efficient, any form of help would be appreciated. Thank You. Also, I tried adding double quotes … -
Django Formset not correctly populating form data
I am trying to set up a page where a Return can be made to an order, with as many ReturnItems as needed. The empty forms for additional ReturnItems are generated by JavaScript passing in the empty form HTML string created by the formset factory. When the forms are properly filled in, it works as expected. However, when I try to submit with multiple ReturnItems forms being empty, the validation of the forms do not work properly. What I don't understand is that even though the request.POST data is correct the 'reason' and 'opened' field are not populated for the forms which causes the forms to be empty and skipped, instead of raising a ValidationError for missing the product name/code. Any help or suggestions would be useful, thanks. Example of request.POST data <QueryDict: {'csrfmiddlewaretoken': ['token'], 'first_name': ['first'], 'last_name': ['last'], 'email': ['e@email.com'], 'telephone': ['12345'], 'order_id': ['123'], 'order_date': ['2022-10-05'], 'form-TOTAL_FORMS': ['2'], 'form-INITIAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['1'], 'form-MAX_NUM_FORMS': ['15'], 'form-0-product_name': ['prod1'], 'form-0-product_code': ['code1'], 'form-0-quantity': ['2'], 'form-0-reason': ['1'], 'form-0-opened': ['False'], 'form-1-product_name': ['prod2'], 'form-1-product_code': ['code2'], 'form-1-quantity': ['3'], 'form-1-reason': ['1'], 'form-1-opened': ['False'], 'comment': ['comment']> Views.py def return_view(request): sitekey = settings.H_CAPTCHA_SITEKEY ReturnItemFormSet = formset_factory( ReturnItemForm, extra=0, min_num=1, max_num=15, validate_min=True, absolute_max=15, ) return_form = ReturnForm() return_item_formset = ReturnItemFormSet() empty_form … -
Django: How to use CreateView in one model and at the same time update a field in a second model. (Using a form in templates only)
I couldn't find a direct answer elsewhere. I created a Group Model and a GroupMember Model. My goal is that a user creates a Group via a form in templates, then automatically in the GroupMember model the fields should be filled. In particular the field is_admin should be 1, although its default value is set to 0. How to tell CreateGroupView to fill the GroupMember model? views.py class CreateGroupView(LoginRequiredMixin, CreateView): fields = ("name","description") model = Group class SingleGroupView(DetailView): model = Group class ListGroupView(ListView): model = Group models.py class Group(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default='') members = models.ManyToManyField(User,through="ProjectMember") def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("groups:single", kwargs={"slug": self.slug}) class GroupMember(models.Model): user = models.ForeignKey(User,related_name='user_groups',on_delete=models.CASCADE,) group = models.ForeignKey(Group, related_name="memberships",on_delete=models.CASCADE,) is_admin = models.BooleanField(default=False) def __str__(self): return self.user.username class Meta: unique_together = ("group", "user") my template to create a Group <form class="m-5" method="POST" action="{% url 'groups:create' %}" id="groupForm"> {% csrf_token %} <div class="form-group"> <label for="id_name">Name</label> <input type="text" name="name" maxlength="255" class="form-control" placeholder="Name" title="" required id="id_name"> </div> <div class="form-group"> <label for="id_description">Description</label> <textarea name="description" cols="40" rows="10" class="form-control" placeholder="Description" title="" id="id_description"></textarea> </div> <input type="submit" value="Create" class="btn btn-primary btn-large"> </form> the urls.py urlpatterns = … -
Possible Unhandled Promise Rejection (id: 0): [AxiosError: Network Error] - React Native and Django
I'm trying to get the data from Django backend for my React Native project but im getting this error Possible Unhandled Promise Rejection (id: 0): [AxiosError: Network Error] im new to react native and django but ive done this before in react js but i dont know why i cant get it to work here Here's My React Native Code import React, { useState, useEffect } from "react"; import axios from "axios"; import { StyleSheet, ScrollView, View, Text } from "react-native"; // Components import ProductCard from "../components/ProductCard"; export default function HomeScreen({ navigation }) { const [products, setProducts] = useState([]); useEffect(() => { async function fetchProducts() { const { data } = await axios.get("http://127.0.0.1:8000/api/products/"); setProducts(data); } fetchProducts(); }, []); return ( <View style={styles.container}> <ScrollView style={styles.scrollView}> {products.map((product) => ( <View style={styles.productsContainer}> <ProductCard product={product} navigation={navigation} /> </View> ))} </ScrollView> </View> ); } I also added these to settings.py INSTALLED_APPS = [ "corsheaders", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", ] CORS_ALLOW_ALL_ORIGINS = True -
Integrate Stripe payment flow into django
I’m trying to integrate stripe custom payments flow into my Django ecom website as PayPal isn’t as good but the docs (https://stripe.com/docs/payments/quickstart?lang=python) for python are in the flask framework. Does anyone have boilerplate code for handling a simple transaction for this in Django (views, template etc.) -
ImportError: cannot import name 'KeyTextTransform' from 'django.contrib.postgres.fields.jsonb'
What is the new import for: ImportError: cannot import name 'KeyTextTransform' from 'django.contrib.postgres.fields.jsonb' I did some internet searching and didn't find an immediate result for the error. I am trying to upgrade from django 3.2 to django 4.1.2 -
Django Group by multiple times
In my Django models, I have class Tracker(models.Model): grade = models.ForeignKey(Grade, on_delete=models.CASCADE) teacher = models.ForeignKey(User, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) BREAK_TYPE_CHOICES = [ ('1', 'Toilet Pass'), ('2', 'Hall Pass'), ('3', 'Doctor Pass'), ] break_type = models.CharField(max_length=10, choices=BREAK_TYPE_CHOICES) start_date_time = models.DateTimeField(auto_now_add=True) end_date_time = models.DateTimeField(auto_now=True) status = models.BooleanField(default=False) I need to find all the breaks given in a day, group by teachers with a break up on the basis of break type. Currently, I can get breaks given in a day and group them by teachers. breaks_today = Tracker.objects.filter(status=True, start_date_time__gte=date_from, end_date_time__lte=date_to) breaks_today = breaks_today.values('teacher').order_by('teacher').annotate(count=Count('teacher')) How do I proceed with the next step, i.e. group by break types, then group by teacher? -
how to get over all kms using property method in django for render into templates?
Greeting developers,Actually i want to render overall km travel by particular vehicle from using @property method in django model . here is my models class Log(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) driver = models.ForeignKey(Driver, on_delete=models.CASCADE) date = models.DateField(default=timezone.now, blank=True, null=True) and related to that models i have onther models class Logsheet(models.Model): log = models.ForeignKey(Log, on_delete=models.CASCADE, related_name="logsheets") trip = models.IntegerField(blank=False, null=False) distance_from = models.FloatField(blank=True, null=True, default=0.0) distance_to = models.FloatField(blank=True, null=True, default=0.0) time_from = models.TimeField(blank=True, null=True) time_to = models.TimeField(blank=True, null=True) source = models.CharField(max_length=100, blank=True, null=True) destination = models.CharField(max_length=100, blank=True, null=True) doeking_km = models.FloatField(blank=True, null=True, default=0.0) def save(self, *args, **kwargs): self.doeking_km = int(float(self.distance_to)) - int(float(self.distance_from)) super(Logsheet, self).save(*args, **kwargs) where is doeking km is daily kms .. Problems I want to render over all km travel by particual vehicle using @property method so i can easily render it templates help me guys. -
Django Unit Testing - How to test all instances in a model?
I want to test all instances in a DB using Django. I have a python script that populates the DB and I want to test every single instance if it pass the test. I provide here a dummy tests.py: from django.test import TestCase from app_core.models import Item # Item model fields are: pk, first, second class PairTestCase(TestCase): def setUp(self): # This script populates the DB creating several Item instances from app_core.init import init_items def test_pair_elems_different(self): """First and second fields MUST be different inside the instance""" item = Item.objects.get(pk=1) self.assertNotEqual(item.first, item.second) As you can see, I just tested a single instance. Let's suppose the DB contains 1000 Item instances, what is the best way to test them all? The only solution that pops up in my mind is using a simple FOR loop inside test_pair_elems_different, iterating all object and comparing each instance. Is this approach correct in the context of unit testing best practices/principles? -
Complex query to calculate user balance
I have the following model (that is simplified): class CoinTransaction(models.Model): class TransactionTypes(Enum): purchase_of_coins = ('pu', 'Purchase of Coins') # Will have a positive amount conversion_into_money = ('co', 'Conversion Into Money') # Will have a negative amount earning = ('ea', 'Earning') # Will have a positive amount expense = ('ex', 'Expense') # Will have a negative amount @classmethod def get_value(cls, member): return cls[member].value[0] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='coin_transactions') amount = models.IntegerField() transaction_type = models.CharField(max_length=2, choices=[x.value for x in TransactionTypes]) I want a query to get two values related to a given user: earned_coins and other_coins, without saving their value into the User model. The query should calculate these values exactly like this: earned_coins = 0 other_coins = 0 for transaction in CoinTransaction.objects.filter(user=user).order_by('creation_date'): amount = transaction.amount if transaction.transaction_type in [CoinTransaction.TransactionTypes.get_value('conversion_into_money'), CoinTransaction.TransactionTypes.get_value('earning')]: earned_coins = max(earned_coins + amount, 0) elif transaction.transaction_type in [CoinTransaction.TransactionTypes.get_value('purchase_of_coins'), CoinTransaction.TransactionTypes.get_value('expense')]: other_coins += amount if other_coins < 0: earned_coins = max(earned_coins + other_coins, 0) other_coins = 0 -
ValueError when using Django Model to import data from file into legacy database
I would like to use Django’s models to import data from newly arriving files into a legacy database. This should happen in the background whenever the user opens the main page of my app. Unfortunately, I am stuck with an “ValueError: Cannot assign "'Student_2": "Exam.student_id" must be a "Student" instance.” I know there are plenty of questions regarding how to solve this error but I still cannot figure out how to solve this in my case. I am not allowed to change anything about the legacy database and I have no influence on the format of the new files. This is how my database looks like: Here are some example data: This is how a file with new data looks like: This is how my models look like: class School(models.Model): school_id = models.CharField(primary_key=True, max_length=100) class Meta: managed = False db_table = 'school' class Student(models.Model): student_id = models.CharField(primary_key=True, max_length=100) school_id = models.ForeignKey('School', models.DO_NOTHING, db_column='school_id') class Meta: managed = False db_table = 'student' class Exam(models.Model): result_id = models.CharField(primary_key=True, max_length=100) grade = models.CharField(max_length=100, blank=True, null=True) student_id = models.ForeignKey('Student', models.DO_NOTHING, db_column='student_id') class Meta: managed = False db_table = 'exam' This is how I try to import the data: new = new_file.txt result_id = linecache.getline(new, … -
How to get value error of datetime in python for an if statement
I'm currently making an appointment app as a hobby and working on a portion of my app where when a user clicks on a day it returns all appointments they have for that day. I'm using datetime in the django filter and noticed a small bug. ValueError: day is out of range for month Pretty much my code in brief looks like this: dateArr = selected_date.split('-') startDate = datetime.datetime(int(dateArr[0]), int(dateArr[1]), int(dateArr[2]), 0, 0, 0, tzinfo=timezone.utc) endDate = datetime.datetime(int(dateArr[0]), int(dateArr[1]), int(dateArr[2]) + 1, 0, 0, 0, tzinfo=timezone.utc) I know I could write a helper function that checks to see if it's the last day of a month and then also add 1 to the month, or reset month to 1 if its dec 31. But is there a way to get the value code for datetime errors to use in an if statement? I looked through the docs but don't see anything. maybe value codes are a python thing and I should be looking somewhere else? thanks in advance! EDIT*** Think i found the answer to my own question here - https://docs.python.org/3/tutorial/errors.html - for anyone from the future.