Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
List only unassigned values for many to many field in Django
I have two models as follows: class Fruit(models.Model): name = models.CharField(max_length=20) class Season(models.Model): name = models.CharField(max_length=20) fruits = models.ManyToManyField(Fruit, related_name='seasonal_fruit') I want to add the fruits to the Season if only they are not assigned to any other Season object. Also, I want to display the list of these distinct (i.e. not assigned to any other Season object) in the SeasonAdmin. How can I achieve this? -
Django Rest Framework - serializers.SlugRelatedField does not return field value
I have the following Car model in my Django Rest Framework project: from django.db import models from django.contrib.auth.models import User class Car(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100) driver = models.ForeignKey(User, related_name='cars', on_delete = models.CASCADE) def __str__(self): return self.name class Meta: ordering = ['created'] As you can see, the Car model has a foreignkey relationship with the built-in User model. The field is called driver. Now, using the serializer class I also wanted to print out the username of the driver. Therefore, I used serializers.SlugRelatedField like this: class CarSerializer(serializers.ModelSerializer): username = serializers.SlugRelatedField(read_only=True, slug_field='username') class Meta: model = Car fields = ['id', 'name', 'username'] But in the JSON output I can not see the username value: [ { "id": 1, "name": "BMW" }, { "id": 2, "name": "Audi" } ] What is wrong here? -
How can I access the serializer in extra actions?
I have the following two classes and I want two merge EventInvitationCreateView into EventInvitationViewSet. However, I am struggling to bring perform_create into create_invitation as I still need to access serializer. Do you have any input on how to achieve that? class EventInvitationCreateView(CreateAPIView): serializer_class = InvitationSerializer permission_classes = [RetoolPermission] queryset = Invitation.objects.none() def perform_create(self, serializer): email = serializer.validated_data["email"] event = self.request.event invitation_exists = Invitation.objects.filter( email__iexact=email, event=event ).exists() if invitation_exists: raise ValidationError("Email already exists") serializer.save(event=event) class EventInvitationViewSet( mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet ): permission_classes = [RetoolPermission] serializer_class = InvitationSerializer filter_backends = [filters.SearchFilter] search_fields = ["email"] queryset = Invitation.objects.none() def get_queryset(self) -> QuerySet: return self.request.event.invitations.all() @action(detail=True, methods=["post"]) def create_invitation(self, request, pk=None): [...perform_create] -
Celery worker stops when console is closed
I am trying to run Celery in development environment, on a cloud server. I am connecting to the machine using remote SSH, and starting Celery worker with the following comand: celery -A myapp worker -l info -f logs/celery.log Everything works fine at this point, but the worker stops a few seconds after the console window is closed (ssh connection closed). How do I keep the worker running, as having an opened SSH connection permanently is not an option? celery.py import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('uiforms') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() tasks.py import requests from celery import shared_task import json def auth(): headers = {"someheaders"} data = { "somedata" } r = requests.post("url", data=data, headers=headers) return r.json()['access_token'] @shared_task def add_queue_item(acces_token=None, content=None): acces_token = auth() headers = { "Content-Type": "application/json", "Authorization": f"Bearer {acces_token}", } data = json.dumps(content) r = requests.post("url", data=data, headers=headers) cellery logs: [2020-11-20 08:55:13,548: INFO/MainProcess] celery@localhost ready. [2020-11-20 08:55:13,549: INFO/MainProcess] Received task: dlaforms.tasks.add_queue_item[517d8785-d08c-48a3-9475-b1c728daf66d] [2020-11-20 08:55:13,550: INFO/MainProcess] Received task: dlaforms.tasks.add_queue_item[3cdc3b8e-dbea-4f69-bb3a-d87668fb7804] [2020-11-20 08:55:14,181: INFO/ForkPoolWorker-1] Task dlaforms.tasks.add_queue_item[517d8785-d08c-48a3-9475-b1c728daf66d] succeeded in 0.5300460010184906s: None [2020-11-20 08:55:14,702: INFO/ForkPoolWorker-1] Task dlaforms.tasks.add_queue_item[3cdc3b8e-dbea-4f69-bb3a-d87668fb7804] succeeded in 0.5188984139822423s: None rabbitmq logs: 2020-11-20 08:42:34.239 [info] <0.16979.4> accepting AMQP connection … -
Best JavaScript Frawework to Use With Django
I have a general question about JavaScript frameworks and Django. Most of the time when I have been developing a project in Django, I have used J Query to add dynamic functionality to the rendered HTML templates, but from what I understand J Query should be avoided these days in the 2020s. My question would be what is the best alternative to use instead? I have previously made projects where I have used the Django REST Framework to build a back end REST API and then have built a front end in React which has worked fine, but the thing with this is that I have to host both the back end and front end separately. What would I be best doing if I wanted to render the front end using Django, but want the same sort of functionality that J Query allows for. Is the only option plain vanilla JavaScript or is there something new now? Please let me know if this should be posted in a different community as it is more about a recommendation, but I wasn't sure which community this should be posted under. -
Unity3d/django : You are seeing this message because this HTTPS site requires a “Referer header” to be sent by your Web browser, but none was sent
I am using a C# script to communicate to django https://mywebsite.co.uk/ from Unity3d editor using UnityWebRequest. My script: using System; using System.Collections; using System.Collections.Generic; using System.Text; using TMPro; using UnityEditor; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; //for reference - with some code if you would rather post a form public class WebFormPost: MonoBehaviour { public TMP_Text resultText; public string webAPIserver = "https://mywebsite.co.uk/"; private void Awake() { resultText.text = "Getting results from: " + webAPIserver +"\n"; } public void GetWebPage() { resultText.text += "Getting some results .... \n"; StartCoroutine(GetWebResult(resultText)); } public IEnumerator GetWebResult(TMP_Text results) { WWWForm form = new WWWForm(); //string mimeType = "image/jpg"; //string imageName = "screenshot.jpg"; //byte[] imageToUpload = image.EncodeToJPG(); // form.AddBinaryData ( "img", imageToUpload, imageName, mimeType); string searchURL = webAPIserver; results.text += "about to send. . . \n"; using (UnityWebRequest w = UnityWebRequest.Post(searchURL, form)) { yield return w.SendWebRequest(); if (w.isNetworkError) { Debug.Log(w.error); } else { Debug.Log("POST web call successful!"); // Print Headers StringBuilder sb = new StringBuilder(); foreach (System.Collections.Generic.KeyValuePair<string, string> dict in w.GetResponseHeaders()) { sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n"); } Debug.Log("received headers: "); Debug.Log(sb.ToString()); // Print Body var downloadedText = w.downloadHandler.text; Debug.Log("received body text: "); Debug.Log(downloadedText); results.text = downloadedText; } } }} However, when I run the code I get the … -
ModuleNotFoundError using LayerMapping
Using ogrinfo -so I've found the structure of the shapefile and based on this structure I've created a model: from django.contrib.gis.db import models class Villages(models.Model): . . . After that I've created the load.py as mentioned here inside the same directory of models.py: from pathlib import Path from django.contrib.gis.utils import LayerMapping from .models import Villages villages_mapping = { . . . } villages = Path(__file__).resolve().parent / 'gis' / 'villages.shp' def run(verbose=True): lm = LayerMapping(Villages, villages, villages_mapping, transform=False) lm.save(strict=True, verbose=verbose) Then, I try to use load.py: /geodata$ python3 load.py but I see this error: Traceback (most recent call last): File "load.py", line 3, in from .models import Villages ModuleNotFoundError: No module named 'main.models'; 'main' is not a package The app name is geodata, I've added this app inside settings.py and finalized the creation of the table with makemigrations and migrate. I'm using Django 3.0.7. I don't understand where is the problem -
Django filter date > datetime.now
I have a view that displays a list sorted by date. I would like to make a filter to display values where the date is greater than the current date. How to do it correctly? class UpcomingEvents(generics.ListAPIView): queryset = Event.objects.all().order_by('start_date') serializer_class = EventSerializer -
Flask application folder structure like Django
Is it possible to a Flask application looks like django application folder structure. I just want to organize the folders and separate the MVC part of the code and also I can use a class base which is kinda looks good vs on one file where your model, route and views live on single file. -
How to filter a field from a child model which has a foreign key in parent model in django rest framework?
I am trying to build an API in drf for listing the different travel packages. I have two models. The package is a parent model and Topactivities is a child model which has a foreign key to the Package model. Now when I hit localhost:8000/api/allpackages api I need to list all the packages which is not a problem. The problem is I want to filter the packages with activities title in the query. For eg: If I do localhost:8000/api/allpackages?activities=trekking, I need to show all the packages which have the activity of trekking. However, activities are not a field in the package. I am trying to use filter backends. Here are my models: class Package(models.Model): destination = models.ForeignKey(Destination, on_delete=models.CASCADE) package_name = models.CharField(max_length=255) featured = models.BooleanField(default=False) price = models.IntegerField() duration = models.IntegerField(default=5) discount = models.CharField(max_length=255, default="15% OFF") discounted_price = models.IntegerField(default=230) savings = models.IntegerField(default=230) special_discount = models.BooleanField(default=False) rating = models.IntegerField(choices=((1, 1), (2, 2), (3, 3), (4, 4), (5, 5)) ) image = models.ImageField(blank=True) thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) content =RichTextField() highlights = RichTextField() itinerary = RichTextField() image_1= models.ImageField(blank=True,null = True) image_2= models.ImageField(blank=True,null = True) image_3= models.ImageField(blank=True,null = True) date_created = models.DateField() def __str__(self): return self.package_name class TopActivities(models.Model): package = models.ForeignKey(Package, … -
DJANGO - Error with complex AND, OR condition in 1 FILTER, but works with many FILTERS ? Why?
I had this query which I did quite nice query = LeadtimeConfig.objects.filter(last_mile__isnull = True, Q(origin = _origin_area) | Q(origin__isnull = True), Q(destination =_destination_area) | Q(destination__isnull=True), Q(delivery_type = _delivery_type) | Q(delivery_type__isnull = True) | Q(delivery_type = '') ) However, I keep receiving this error query = LeadtimeConfig.objects.filter(last_mile__isnull = True, Q(origin = _origin_area)|Q(origin__isnull = True), Q(destination =_destination_area)|Q(destination__isnull=True), Q(delivery_type = _delivery_type) | Q(delivery_type__isnull = True) | Q(delivery_type = '') ) ^ SyntaxError: positional argument follows keyword argument But when I did this : query = LeadtimeConfig.objects.filter(last_mile__isnull = True) .filter(Q(origin = _origin_area) | Q(origin__isnull = True)) .filter(Q(destination =_destination_area) | Q(destination__isnull=True)) .filter(Q(delivery_type = _delivery_type) | Q(delivery_type__isnull = True) | Q(delivery_type = '')) It works -
how can users upload file into Django model?
With these codes, I want each user to be able to upload their own file in their own model forms.py: class sp_UserNewOrderForm(forms.Form): file= forms.FileField() models.py: class sp_Order(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.owner.username class sp_OrderDetail(models.Model): order = models.ForeignKey(sp_Order, on_delete=models.CASCADE) file= models.FileField() def __str__(self): return self.order.owner.username views.py: @login_required def add_user_order(request): new_order_form = sp_UserNewOrderForm(request.POST or None) if new_order_form.is_valid(): order = sp_Order.objects.filter(owner_id=request.user.id).first() if order is None: order = sp_Order.objects.create(owner_id=request.user.id) file= new_order_form.cleaned_data.get('file') order.sp_orderdetail_set.create(file=file) # todo: redirect user to user panel # return redirect('/user/orders') return redirect('/') return redirect('/') HTML: <form method="post" action="/add_sp"> {% csrf_token %} {{ form.count }} <button type="submit" class="btn btn-primary container"> upload </button> </form> But these codes do not create the model. what is the problem? -
How to add picture into datatables?
I'm using datatables to show the data from API which I saved in my local database. I want to add images to every record when click on some edit button to show the form and to have the possibility to browse picture in my machine and render it in another column in datatables. Any idea or resource how to achieve this? my current jQuery script: <script> $(document).ready(function() { var data; fetch("http://192.168.1.80:8000/fetchapi/") .then(response => response.json()) .then(json => data = json) .then(() => {console.log(data); $('#datatable').DataTable( { data: data.users, deferRender: true, scrollY: false, scrollX: false, scrollCollapse: true, scroller: true, columns: [ { data: "user_id" }, { data: "user_name" }, { data: "user_email" }, { data: "status" }, { data: "user_type" }, ] } ) }) } ); $(document).ready( function () { $.fn.DataTable.ext.pager.numbers_length = 5; var table = $('#example').DataTable({"pagingType": "full_numbers"}); } ); </script> -
(Hidden field author) This field is required
I followed this django tutorial on how to restrict other users in the blog post posts. (The Video Link: https://www.youtube.com/watch?v=TAH01Iy5AuE&list=PLCC34OHNcOtr025c1kHSPrnP18YPB-NFi&index=17) But I get this message when I try to post (Hidden field author) This field is required? This is my views.py file from .forms import PostForm, EditForm class AddPostView(CreateView, LoginRequiredMixin): model = Post form_class = PostForm template_name = "add_post.html" # fields = "__all__" This is my forms.py file from .models import Post, Category from django import forms # choices = [('uncategorized', "uncategorized"), ("gaming", "gaming"), ("youtube", "youtube"),] choices = Category.objects.all().values_list('name', 'name') choice_list = [] for item in choices: choice_list.append(item) class PostForm(forms.ModelForm): class Meta: model = Post fields = ("title", "title_tag", "author", "category", "body") widgets = { "title": forms.TextInput(attrs={"class": "form-control", "placeholder": "Title"}), "title_tag": forms.TextInput(attrs={"class": "form-control", "placeholder": "Title Tag"}), "author": forms.TextInput(attrs={"class": "form-control", "id": "Rashaad", "value": "", "type": "hidden"}), # "author": forms.Select(attrs={"class": "form-control"}), "category": forms.Select(choices=choice_list, attrs={"class": "form-control"}), "body": forms.Textarea(attrs={"class": "form-control", "placeholder": "Body"}), } class EditForm(forms.ModelForm): class Meta: model = Post fields = ("title", "title_tag", "category", "body") widgets = { "title": forms.TextInput(attrs={"class": "form-control", "placeholder": "Title"}), "title_tag": forms.TextInput(attrs={"class": "form-control", "placeholder": "Title Tag"}), # "author": forms.Select(attrs={"class": "form-control"}), "category": forms.Select(choices=choice_list, attrs={"class": "form-control"}), "body": forms.Textarea(attrs={"class": "form-control", "placeholder": "Body"}), } my add_post.html file {% extends 'base.html' %} {% block content … -
Django allow anonymous ajax request to access a Generic View
This is what I've got so far: from django.views.generic import View from django.views.decorators.csrf import csrf_exempt class ConfigurationView(View): @csrf_exempt def dispatch(self, *args, **kwargs): return super(ConfigurationView, self).dispatch(*args, **kwargs) def get(self, request): ... However, when I make an ajax get request to this view I am not able to access the get method function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } $.ajax({ url: "https://{{ domain }}/configure", headers: { 'X-CSRFToken': getCookie('csrftoken') }, crossDomain: true, data: { email: "{{ email }}", }, dataType: "json" }) I think I am sending the csrftoken correctly and I shouldn't really need the csrf_exempt, but either way the request gets a redirection to the login page. Any help would be highly appreciated. -
Autocomplete search in Django
I am using autocomplete function to filter data, from this site: https://api.jqueryui.com/autocomplete/ First I am using Django. everything work perfectly with this method if it is in page with no extends. but if I use it in page which is inside a block extends it doesn't work!?? {% extends 'Home/base.html' %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'Home/plugins/jquery-ui/jquery-ui.css' %}"> <script src="{% static 'Home/plugins/jquery/jquery.js' %}"></script> <script src="{% static 'Home/plugins/jquery-ui/jquery-ui.js' %}"></script> So it works when I delete {% extends 'Home/base.html' %}? what is the problem? -
django-filters multiple related fields: filter down the fields
I am using django-filters module to filter my table. I can filter the data but can not bind the fields. After I filter by one field, another field should contain only related values. Table I am filtering As you can see in the picture when I filter by the field "Şube", I can see the related values that should be contained by "Kaynak" field on top but "Kaynak" dropdown still contains all its values. My models: class Subeler(models.Model): subeadi = models.CharField(max_length=200) class AltKaynaklar(models.Model): tali_adi_x = models.CharField(max_length=200) subeadi = models.ForeignKey(Subeler, null=True, on_delete=models.SET_NULL, related_name="bagli_kaynaklar") class AKMutabakat(models.Model): tali_adi_x = models.ForeignKey(AltKaynaklar, null=True, on_delete=models.SET_NULL) subeadi = models.ForeignKey(Subeler, null=True, on_delete=models.SET_NULL) ..... My filter: class UretimFiltre(django_filters.FilterSet): class Meta: model = AKMutabakat fields = ['subeadi', 'tali_adi_x', 'trafik_mi', 'yil', 'ay'] My views.py: def mutabakat(request): context = {} kaynaklar = AltKaynaklar.objects.filter(subeadi=request.GET.get('subeadi')) sources = AKMutabakat.objects.all() myFilter = UretimFiltre( request.GET, queryset=sources, ) context['myFilter'] = myFilter I can query related "Kaynak" values like in the picture but can't put it inside the filter. Can anybody help? -
The proper way of getting the value of a TimeField in Django
Imagine that in a Educational Management System I have created a form for entering the details for a ,let say, course. After I save it to the database(in my case postgres) I want to provide the user with the opportunity to edit the previously saved form. So I have to initialise a form with the initial values that user has previously entered. Everything is Alright but the problem is that I cannot format the the TIME input (let say the time that course starts) received from the database into a proper shape to be suitable for in my html. So the initial value is not shown in the time input.How can I solve this problem? -
how to prevent user from going back to form (all forms login, edit post, etc.) after submission in django?
I'm new to django and I'm stuck with a problem. Please help me solve it. Problem: Whenever I fill a form, be it a login form, edit post form, create post form, etc..If I press browser's back button, It takes me back to it. What I want: Redirect the user to somewhere else rather than taking them back to form. Is there any way to perform it in django ? I want to use CBVs only "and yes, I don't wanna disable browser back button !" Code: views.py class CreatePost(LoginRequiredMixin, UserPassesTestMixin, CreateView): model = Post template_name = 'blog/create_post.html' fields = ('category', 'title', 'meta_title', 'meta_description', 'content', 'image', 'image_alt_text') user_check_failure_path = 'blog-home' def test_func(self): return self.request.user.is_superuser def handle_no_permission(self): if self.request.user.is_authenticated: messages.error(self.request, 'Permission Denied ! Only SUPERUSER can access this page', 'danger h4') return redirect('blog:blog-home') else: return redirect('accounts:login') class Login(views.LoginView): template_name = 'accounts/login.html' redirect_authenticated_user = True -
i have an issue in djangorest profile_data = validated_data.pop('profile') KeyError: 'profile'
class UserSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('first_name', 'last_name', 'phone_number', 'age', 'gender') class UserRegistrationSerializer(serializers.ModelSerializer): profile = UserSerializer(required=False) class Meta: model = User fields = ('email', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create_user(**validated_data) UserProfile.objects.create( user=user, first_name=profile_data['first_name'], last_name=profile_data['last_name'], phone_number=profile_data['phone_number'], age=profile_data['age'], gender=profile_data['gender'] ) return user -
Using Django F expression with Case, When expression
I have a Django model like # app/models.py class tbl_invoice(models.Model): invoice_id = models.IntegerField(blank=True, null=True) client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE) invoice_number = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True) amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) paid_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) balance = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) date_of_payment = models.DateField(blank=True, null=True) status = models.CharField(max_length=50, default='', blank=True, null=True) I have another view in which I am saving payment record, I want to update status as Paid or Unpaid depending on if the difference between the user-entered amount and balance is 0 or not currently, this is what I have done #app/views.py if form.is_valid(): post = form.save(commit=False) # rest of the logic goes here post.save() # this data is saved in another model, after that I update invoice model tbl_invoice.objects.filter(invoice_id=someIdHere).update(paid_amount=F('paid_amount')+post.amount, date_of_payment=post.date, balance=F('balance')-post.amount, status=Case( When(balance=F('balance')-post.amount==0, then=Value("Paid")), When(balance=F('balance')-post.amount!=0, then=Value("Unpaid")), )) this query is updating status as blank. however, using only the F expression to update amount and balance is working fine tbl_invoice.objects.filter(invoice_id=someIdHere).update(paid_amount=F('paid_amount')+post.amount, date_of_payment=post.date, balance=F('balance')-post.amount the above statement is working fine surely I am making some obvious mistake that I can't figure out. How can I use the F expression with Case?? -
Python - \x characters while reading from an uploaded file
I am using python3.6 and django 2.2.6 in the backend. I am uploading a .odt file without any encoding. When I do this print(type(request.FILES['labfile'])) print(request.FILES['labfile'].read()) It gives me <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> And this: https://pastebin.com/4WiueuMb The original contents of the odt file is https://pastebin.com/6qT1XWJR I tried doing request.FILES['labfile'].read().decode("utf-8") and I got 'utf-8' codec can't decode byte 0xd2 in position 12: invalid continuation byte I thought \x could mean hex and tried decoding using .decode("hex") and codecs.decode() but that didn't work either. Now it seems like the data is somehow related to xml, but I am not having any idea of how to decode. Any leads are highly appreciated and thankful. Thanks in advance. -
I want to show cateogory wise product
I am trying to make an e-commerce project for that reason I want to show category wise product but I am really confused have no faith in me that I will able to do that so I need some guide or help for this I just created a view I ama giving this below: cart = request.session.get('cart') if not cart: request.session['cart'] = {} #products = None cats = Category.get_categories() brands = Brand.get_brands() sliders = Slider.objects.all() offers = Offer.objects.all() categoryID = request.GET.get('category') brandID = request.GET.get('brand') if categoryID: products = Product.get_products_by_category(categoryID) else: products = Product.get_all_products() if brandID: proucts = Product.get_brands_by_products(brandID) else: products = Product.get_all_products() products = [] catprods = Product.objects.values('category', 'id') cats = {item['category'] for item in catprods} for cat in cats: product = Product.objects.filter(category=cat) products.append(['products']) args = { 'products':products, 'cats': cats, 'brands': brands, 'sliders':sliders, 'offers':offers } return render(request, 'Home/index.html', args) Its giving me an error. don't know what to do please help -
Need help in resolving the error 'The QuerySet value for an exact lookup must be limited to one result using slicing'
I am relatively new to django and I have got an error which I am unable to understand. I have 3 models namely customer, services and uses. I want to fetch the services used by a customer. I am doing this via the uses model by querying the models(specifically using the filter method). However I am getting the following error ValueError at /employee/view_customer/ The QuerySet value for an exact lookup must be limited to one result using slicing. Here are my models Customer class Customer(models.Model): firstname = models.CharField(max_length=15) lastname = models.CharField(max_length=15) age = models.IntegerField() sex = models.CharField(max_length=10) phoneno = models.IntegerField() emailid = models.CharField(max_length=25) address = models.CharField(max_length=50) children = models.IntegerField() adults = models.IntegerField() roomtype = models.CharField(max_length=10) aadharno = models.CharField(max_length=15) daysstayed = models.IntegerField() date_visited = models.DateTimeField(default=timezone.localtime()) def __str__(self): if self.firstname == None: return '' else: return str(self.id) Services class Services(models.Model): service_name = models.CharField(max_length=15) price = models.IntegerField() def __str__(self): if self.service_name == None: return '' else: return str(self.service_name) Uses class Uses(models.Model): customer = models.ForeignKey(Customer,on_delete=CASCADE) service_id = models.ForeignKey(Services,on_delete=CASCADE) time_used = models.TimeField(default=timezone.localtime()) def __str__(self): if self.customer == None: return '' else: return str(self.customer) The function at employee/view_customer def view_customer(request): if request.method == 'POST': customer = Customer.objects.all() uses = Uses.objects.filter(customer_id=customer) services = Services.objects.filter(id=uses) print(services) return render(request,'employee/cust-info.html',{'customer':customer,'services':services}) … -
DB design and ideas for a webserver management system
I'm working on a "(web)server management system" for my local webserver, to learn django on something useful. (Maybe when it's done and other people will be interested, I'll release that as an open source project.) My problem is, I'd like a real-time graphs for CPU/RAM usage and CPU temperature and also history graphs. For the real-time I'd get the data every second, saved it and send it via websockets to clients. But, I dont want one big table of values per second, cos in one year it would have 31.5M rows, that's too much :) So for the history data I probably need just average,max and min values per day (?) But also when I reach some percentage (for example 70%), I should have a log of processes that were consuming the cpu/ram. So I'd have probably a per_sec table, which I'd truncate at midnight after I saved the average,max,min values to a per_day table. Plus I'd have a peaks and peaks_processes tables. Also I'd use some in-memory db for the last 10seconds values - to faster serve the websockets. Or does anybody have any better ideas for the db design? And what else might a real server admin be …