Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use logger for django as module
I am trying to set the logger for django project. I use MyLogger.py to initialize logger myproj/myproj/helper/MyLogger.py import sys import logging from logging import getLogger,StreamHandler,WARNING,INFO logger = getLogger(__name__) logger.setLevel(logging.DEBUG) logger.debug("MyLogger init") // it is shown and try to import logger in my views.py then in my views.py myproj/defapp/views.py from myproj.helpers.MyLogger import logger as _logger def index(request): print("get near start") // it is shown _logger.debug("get near start from logger") //but nothing appears in console. Where should I fix?? -
django orm prefetch_related latest data
Reference: django - prefetch only the newest record? Hi I want to bring only the latest message among the messages I wrote. Models class Room(models.Model): host = models.ForeignKey(Company, related_name="room_host", on_delete=models.CASCADE) member = models.ForeignKey(Company, related_name="room_member", on_delete=models.CASCADE) status = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) class Message(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name="message") sender = models.ForeignKey(USER, on_delete=models.CASCADE, related_name="sender") content = models.TextField() created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) My code last_msg_pk = Message.objects.filter( sender__company_code=user.company_code ).values("id") room = Room.objects.filter( member=request.user.company_code ).prefetch_related( Prefetch( "message", queryset=Message.objects.filter(pk__in=last_msg_pk), to_attr="msg" ), ) for i in room: for j in i.msg: print(j.id) 167 136 89 3... I brought all the messages... I just want to bring a message that I wrote recently. What should I do? -
add instances to a manytomany field in django rest framework
I have a very simple question and I'm surprised it hasn't been asked before on this website. I have the two following models: # models.py class Film(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=150) genre = models.ManyToManyField(Genre) class Genre(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, unique=True) I need to make an API that gets 2 integers, id of movie and id of genre, and adds the said genre to the movie. seems very simple but I don't know how I could do this. I could really use the help. -
Nginx doesn't serve static and media with django and Docker
I need to launch my site in production, so I decided to do it with Docker container(at first time, newbie there) with Postgres, nginx and Django, everything is working inside a container, but on launched site I have in console 404 error with static and media. I did a research, but still haven't found the answer for my case. Could somebody advise what I need to fix there? There is my Dockerfile ########### # BUILDER # ########### # pull official base image FROM python:3.9.6-alpine as builder # set work directory WORKDIR /usr/src/my_shop # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 and Pillow dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev jpeg-dev zlib-dev # && pip install Pillow # lint RUN pip install --upgrade pip RUN apk add build-base python3-dev py-pip jpeg-dev zlib-dev ENV LIBRARY_PATH=/lib:/usr/lib # install dependencies COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/my_shop/wheels -r requirements.txt ######### # FINAL # ######### # pull official base image FROM python:3.9.6-alpine # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup -S app && adduser -S app -G app # create the appropriate … -
Is there a faster way of uploading multiple files in Django?
I have a django project where the client can upload multiple files at once. My problem is that for each uploaded file I'm creating a model object - one at a time. Is there a way to do this with bulk create or some other method that is faster. Views.py: images = request.FILES.getlist('images') xmls = request.FILES.getlist('xmls') jsons = request.FILES.getlist('jsons') for image in images: img_name = (str(image).split('.')[0]) dp_name = dataset_name+'-'+img_name if [xml for xml in xmls if img_name+'.' in str(xml)]: xml = [xml for xml in xmls if img_name+'.' in str(xml)][0] else: xml = None if [json for json in jsons if img_name+'.' in str(json)]: json = [json for json in jsons if img_name+'.' in str(json)][0] else: json = None dataset.create_datapoint(image, xml, json, username, dp_name) Models.py: def create_datapoint(self, image, xml, json, username, dp_name): datapoint = Datapoint.objects.create( xml = xml, json = json, name = dp_name, uploaded_by = username, img = image, belongs_to = self, ) self.num_datapoints += 1 datapoint.parse_xml() self.datapoints.add(datapoint) self.save() return -
Logging user's device details in DJango admin
How to log the login user's device, os, ipaddress, location etc. in Django? Is there any library available for this? -
Issue deleting first row in a django_tables2 using TemplateColumn
Relatively new to Django. I am working on a project that has an existing django_tables2 table. I am trying to use TemplateColumn to add a delete button within the table. The code I currently have works for all rows within the table (the values are deleted) except for the first row within the table, which refuses to delete. I can change the table order and always the first row will not delete. When I inspect elements for the new delete button, the only difference I see is that the first row omits the form: <form method="post" action="/en/specimen/1/delete/"> ... </form> I've been trying to get the form to load for the first row, but haven't yet gotten it to work. Here is what I have so far. tables.py: from django_tables2 import tables, TemplateColumn import django_tables2 as tables class SpecimenTable(tables.Table): SpecimenLabel = tables.LinkColumn('specimen_edit', text=lambda record: record.SpecimenLabel, args=[A('id')]) Sample = tables.Column(accessor='Sample.SampleName', verbose_name='Sample') SampleType = tables.Column(accessor='Sample.SampleType', verbose_name='Sample Type') Type = tables.Column(accessor='SpecimenType.name', verbose_name='Specimen Type') Medium = tables.Column(accessor='Medium.name', verbose_name='Medium') class Meta: model = Specimen template_name = "django_tables2/bootstrap4.html" order_by = 'SpecimenLabel' attrs = {"class": "table table-hover"} fields = ['SpecimenLabel', 'Sample', 'SampleType', 'Type', 'Medium', 'delete'] delete=TemplateColumn(template_name='project/tables/specimen_delete.html', verbose_name=_('Delete'), orderable=False) specimen_delete.html <!-- Button trigger modal --> <button type="button" class="btn btn-danger … -
Can't add to ManyToManyField in Django custom task
I have two models in my Django app (Tag and MyModel). MyModel has a ManyToManyField (tags) that uses the Tag model class Tag(models.Model): CATEGORY_CHOICES = ( ('topic', 'topic') ) tag = models.CharField(max_length=100, unique=True) category = models.CharField(max_length=100, choices=CATEGORY_CHOICES) class MyModel(models.Model): id = models.CharField(max_length=30, primary_key=True) title = models.CharField(max_length=300, default='') author = models.CharField(max_length=300) copy = models.TextField(blank=True, default='') tags = models.ManyToManyField(Tag) I have a custom Django management task where I delete the Tags table, get new data, and refresh the Tags table with bulk_create Tag.objects.all().delete() ....get new data for Tag table Tag.objects.bulk_create(new_tags) However after this - if I try to add a tag to an instance of MyModel.tags... mymodel_queryset = MyModel.objects.all() for mymodel in mymodel_queryset mymodel.tags.add(5) ...I get this error: CommandError: insert or update on table "bytes_mymodel_tags" violates foreign key constraint .... DETAIL: Key (tag_id)=(5) is not present in table "bytes_tag". It seems like the Tag table is empty even though I just updated it For some reason deleting and resetting the Tag table prevents me from adding to an instance of MyModel.tags. How can I do this? Note: If I don't first delete and reset the Tags table then I can add to MyModel.tags just fine -
Django Rest Framework sending Request to External API - Expecting value: line 1 column 1 (char 0)
I'm working on an API for my application to send a POST request to an external API. So for example, if my app hits endpoint /myapp/api I want it to call out to an external API and grab some data. In this case, I need this to be a POST request because in order to get the data that I want, I need to pass in some values. I have made this POST call directly to the external API via Postman successfully many times, and I'm now trying to reproduce that in my python code. In my views.py, I have this: class MyAPPViews(APIView): def post(self,request): crt = 'path/to/crtfile' key = 'path/to/keyfile' #here I tried to reproduce the headers from the postman call #as best as I could just to be extra specific headers = { 'Content-Type': 'application/json', 'Accept': '/*/', 'Accept-Encoding': 'gzip,deflate,br', 'Connection': 'keep-alive' } payload = { "unitList": [ "CFQU319303" ] } res = requests.post('external/api/url', headers=headers, data=payload, cert=(crt,key)) print('this is the true http resonse: ',res.status_code) data = res.json() return Response({"status": "success", "data": data}) in my urls.py I have this path('externalAPI',MyAPPViews.as_view()), Now, when I try to go into postman and hit http://127.0.0.1:8000/myapp/externalAPI I get a 500 status code returned and the … -
Python - Django - Heroku - ImportError - cannot import name 'fromshare' from 'socket'
I successfully deployed my app to heroku but now I am getting an error: ImportError at / cannot import name 'fromshare' from 'socket' (/app/.heroku/python/lib/python3.9/socket.py) Looks like it traces back to: File "/app/users/forms.py" in <module> 1. from socket import fromshare I have looked everywhere I can online and have not seen anyone run into this. Any idea how I would fix this? -
running 'heroku login' won't create _netrc file
I am using on a 64-bit system running Windows 11 with Python 3.7 installed and working in a virtual environment where I have installed Django 3.2. I am trying to deploy my project using Heroku. I have tried adding heroku cli 64-bit Windows version to various paths. I have set the env variable HOME with a value of C:\Users<username>_netrc. I have cleaned up the path on each installation so there is only the current path. When I run heroku login from within my project, I get the following error: EPERM: operation not permitted, open 'C:/Users//_netrc Any help here is appreciated -
Django Admin, use list_filter, based on foreing key field
The app have 3 classes at model.py, and it was created a calculated field. class Category(models.Model): name = models.CharField(max_length=255) class Asset(models.Model): category = models.ForeignKey(Category, related_name='categories', on_delete=models.CASCADE) class PortfolioAsset(models.Model): asset = models.ForeignKey(Asset, on_delete=models.CASCADE) @property def category(self): return self.asset.category I tried to add in the admin.py a list_filter: class PortfolioAssetAdmin(admin.ModelAdmin): list_display =('asset', 'category' ) list_filter =(('category', RelatedFieldListFilter),) but i get the error message: "PortfolioAsset has no field named category" I think that is because category in PortfolioAsset is calculated, but don`t know how to solve that. Or if there is any better and working solution. Thanks -
How to get "content_type" using Get File Properties REST API for Azure Files Storage using Python
I'm trying to get the "content_type" property for files in Azure fileshare. I can get "last_modified" and "size" but not "content_type" from azure.storage.file import * from azure.storage.fileshare import * def azure_connect_conn_string(source_file_connection_string, source_share_name): try: share_service = ShareServiceClient.from_connection_string(source_file_connection_string)#ShareServiceClient interact with the account level share_client = share_service.get_share_client(source_share_name) #desired share name is accessed file_service = FileService(connection_string=source_file_connection_string) print("Connection String -- Connected.") return share_client, file_service #returns the share client except Exception as ex: print("Error: " + str(ex)) def fileshare_content_list(connection_instance, directory_name, file_service, share_name): d_client = connection_instance.get_directory_client(directory_name) my_files = d_client.list_directories_and_files() directory_list = [] for file in my_files: if file.get('is_directory'): #cannot get size of directory, only of files file_name = file.get('name') file_lastmod = file.get('last_modified') file_type = 'directory' file_size = 'unknown' else: file_name = file.get('name') file_props = file_service.get_file_properties(share_name, directory_name, file_name) file_lastmod = file_props.properties.last_modified file_size = file.get('size') print(file_name) print(file_lastmod) print(file_size) print(file_props.properties.content_type) def main(): try: azure_connection_string = 'DefaultEndpointsProtocol=https;AccountName=ecpcdmsdatamartexternal;AccountKey=neNa1jtdyVljMN/j403/rHwdYBpPUtKTreeYM4UsKiosiOfKdePgyZdJl8SK9UdAlsXwVvOkNdNWZjnOCyn/lw==;EndpointSuffix=core.windows.net' share_name = "ecdmpext" directory_name = "data" connection_instance, file_service = azure_connect_conn_string(azure_connection_string, share_name) ## List files fileshare_content_list(connection_instance, directory_name, file_service, share_name) print('Done') except Exception as ex: print('main | Error: ', ex) if __name__ == "__main__": main() I get error 'FileProperties' object has no attribute 'content_type' When I try using file.get("content_type") I just get "None". I use file.get() for "size" and "name", for "last_modified" I have to use … -
Javascript function inside Django Loop runs only once
In my template, i generate each table row within a django for loop, I have this function that formats strings the way I want, but it's working only in the first row of the table, I dont know why. -
How to validate form field in django?
I want to make shure that the current value of the "bid" field is not less than current biggest bid. This is my form with a custom clean method. Form: class Place_A_Bid_Form(forms.Form): listing = forms.CharField(widget=forms.TextInput(attrs={"type":"hidden"})) bid = forms.IntegerField(widget=forms.NumberInput(attrs={"class":"form-control"}), min_value=1) def clean_bid(self, biggestBid): bid = self.cleaned_data["bid"] if bid < biggestBid: raise ValidationError("""New bid shouldn't be less than starting bid, or if any bids have been placed then new bid should be greater than current biggest bid""") return bid View: def place_a_bid(request): if request.method == "POST": form = Place_A_Bid_Form(request.POST) user = User.objects.get(username=request.user.username) biggest_bid = Bid.objects.filter(user=user).aggregate(Max("amount")) if form.is_valid(): data = form.cleaned_data user_obj = User.objects.get(username=request.user.username) listing_obj = Listing.objects.get(title=data["listing"]) Bid.objects.update_or_create( user=user_obj, listing=listing_obj, amount=data["bid"] ) return redirect(listing_obj) In view I am extracting current value that I am going to compare to, and I can't figure out how to pass this value to my form field's clean method. Or maybe I'm doing this wrong? So how to do properly this sort of validation? -
How to use Q objcts in annotate tortoise
So simply i have my models Announcement, User, FavoriteAnnouncement class FavoriteAnnouncement(CoreModel): user = fields.ForeignKeyField('models.User', related_name='favorites') announcement = fields.ForeignKeyField( 'models.Announcement', related_name='favorites' ) i want to add an annotated field is_user_fav : Optional[bool] I found a soluition in django ( queryset = queryset.annotate(is_user_fav=ExpressionWrapper( Q(...), output_field=BooleanField(), ),) ) How can i do a similar thing in TortoiseORM ? -
How can I GET the parameters from URL in django
I'm trying to send a parameter by URL and trying to use it in a listview. But I cant GET it in my view. I know I'm doing some stupid mistake, but can't find it. This is the link I'm using in my template: <a class="dropdown-item" href="{% url 'listarmateriales' tipolista='metales' %}">Ver metales This is my url.py: path('listarmateriales/<tipolista>',listarmateriales.as_view(), name='listarmateriales'), And this is where I try to get the "tipolista" in my views.py: class listarmateriales(ListView): template_name = 'materiales/materialeslist.html' def get_queryset(self): if self.request.GET.get('tipolista') is not None: lista=Materiales.objects.all() tipolista=self.request.GET.get('tipolista' '') if tipolista=='metales': Do whatever... else: I have tried some different sintaxis, but the result is always the same, I cant read "tipolista", I have spent a lot of time with this, too much. I know it must be something easy, but, I'm new at this. Thanks in advance -
Call a Django Model class in a plain class as an Instance
I am trying to call a Django model class in a plain class as an Instance, I want to reference some of it's methods : For example I tried this : class Sample(models.Model): title = models.CharField( max_length=40, unique=True, null=True, blank=True) description = models.CharField(max_length=40, unique=True, null=True, blank=True) Then in a plain class below is where I want to access the Model as an instance : class Generator: def __init__(self): self.instance = Sample() I have tried this, though I get this error : mypackage.models.RelatedObjectDoesNotExist Whats the correct way of accessing the model class as an Instance in another class. -
Missing fields of nested serializer
I am using DRF's ModelSerializer and Nested relationships. The issue is that in nested modelserializer, some of the fields defined on, and visible on listing the nested serializer do not show up when listing the parent. Models: class customer(models.Model): cstid = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=35, blank=False) ...SNIPPED class Meta: unique_together = ["name", "mobile", "linkedclinic"] ordering = ['name'] def __str__(self): return self.name class Procedure(models.Model): procid = models.AutoField(primary_key=True, unique=True) timestr = models.DateTimeField(default=timezone.now) template = models.ForeignKey( ProcedureTemplate, on_delete=models.CASCADE, blank=True, null=True) clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE) doctor = models.ForeignKey( doctor, on_delete=models.SET_NULL, blank=True, null=True) customer = models.ForeignKey( customer, on_delete=models.CASCADE, null=False, related_name='procedures') def __str__(self): return f'{self.template} for {self.customer} on {self.timestr}' def eventtime(self): class_date = timezone.localtime(self.timestr) return class_date.strftime("%d-%m-%Y %I:%M %p") Serializers: class FindingSerializer(serializers.ModelSerializer): class Meta: model = Finding depth = 1 fields = [ 'fid', 'fieldheading', 'value', 'linkedprocedure', ] class ProcedureSerializer(serializers.ModelSerializer): finding_proc = FindingSerializer(many=True, read_only=True) class Meta: model = Procedure depth = 2 fields = [ 'procid', 'timestr', 'template', 'clinic', 'doctor', 'customer', 'eventtime', 'finding_proc', ] class customerSerializer(ConvertNoneToStringSerializerMixin, serializers.ModelSerializer): def get_unique_together_validators(self): """Overriding method to disable unique together checks""" return [] class Meta: model = customer depth = 3 biovar_data = Biovariable_dataSerializer( read_only=True, many=True) # many=True is required procedures = ProcedureSerializer( read_only=True, many=True) # many=True is required # allergies … -
Can't filter a field in a translation model of parler app for django
I'm trying to filter a model of images by a certain category. It was all funtioning until I implement the parler app and modify the model to be a tranlated model. Now I can't make the filter work. This are my models: from parler.models import TranslatableModel, TranslatedFields from django.db import models class Categoria(TranslatableModel): translations = TranslatedFields( nombre=models.CharField(max_length=200, null=False, blank=False), ) def __str__(self): return self.nombre class Imagenes(TranslatableModel): translations = TranslatedFields( imagen=models.ImageField(null=False, blank=False), carrusel = models.BooleanField(default=False), nombre=models.CharField(max_length=50, null=False, blank=False), descripcion=models.TextField(max_length=200, null=True, blank=True), fecha_publicacion=models.DateField(), categoria=models.ForeignKey(Categoria, on_delete=models.SET_NULL, null=True, blank=True), ) def __str__(self): return self.nombre This is the view: def gallery(request): category = request.GET.get('category') if category == None: imagenes = Imagenes.objects.all() else: imagenes = Imagenes.objects.filter(translations__categoria=category) categorias = Categoria.objects.all() context = { 'categorias': categorias, 'imagenes': imagenes, } return render(request, 'images/gallery.html', context) And the part of the HTML: {% for cate in categorias %} <a class="dropdown-item" href=" {% url 'gallery' %}?category={{cate.nombre}}">{{cate.nombre}}</a> {% endfor %} When I try this code I get this error: ValueError at /es/gallery/ Field 'id' expected a number but got 'My_Category'. I also try with this line in my view: imagenes = Imagenes.objects.filter(translations__categoria__nombre=category) and get this error: FieldError at /es/gallery/ Related Field got invalid lookup: nombre Every help and suggestion will be apreciated. Thanks -
How to send "time" when sending a message with django channels
I'm a beginner with django-channels working on a chat app. I want the "timestamp" to be shown instantly when a message is sent the room, it only works when I refresh the page as the timestamp gets saved with the models. I tried playing arround with consumers.py and the js code but was not able to send the "timestamp" instantly with the message. * models.py: class Message(models.Model): username = models.CharField(max_length=100) room = models.CharField(max_length=100) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) consumers.py: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from web socket async def receive(self, text_data): data = json.loads(text_data) message = data['message'] username = data['username'] room = data['room'] await self.save_message(username, room, message) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username } ) # Receive message from room group async def chat_message(self, event): message = event['message'] username = event['username'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username': username })) @sync_to_async def save_message(self, username, room, message): Message.objects.create(username=username, room=room, content=message html/js: {{ room_name|json_script:"json-roomname" }} … -
How do I calculate age using Django with a class-based form, templates and gijgo datepicker?
I have read this post and I believe that mine in totally different; Django Datepicker calculate age I am using Django version 4.0.1. I am making use of the Gijgo datepicker to capture the date of birth of the person registering. In my base.html template I added this: <script src="https://unpkg.com/gijgo@1.9.13/js/gijgo.min.js" type="text/javascript"></script> <script>$('.dateinput').datepicker({ format: 'yyyy-mm-dd' });</script> In my register.html template I extends the base template. The form in the register template use a POST method. The code is: <form method="POST"> {% csrf_token %} {{ form|crispy }} With a submit button. The form I use is a class based form in my forms.py file. The code for that looks like this: from django import forms from django.contrib.auth.forms import UserCreationForm from datetime import date selection = [ ('yes', 'Yes'), ('no', 'No') ] class StudentApplicationForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=70) last_name = forms.CharField(max_length=150) date_of_birth = forms.DateField() previous_experience = forms.CharField(widget=forms.RadioSelect(choices=selection)) terms_and_conditions = forms.CharField(widget=forms.CheckboxInput()) class Meta: model = User fields = [ 'first_name', 'last_name', 'date_of_birth', 'terms_and_conditions', 'previous_experience', 'username', 'email', 'password1', 'password2', ] def clean_email(self): email = self.cleaned_data.get('email') email_count = User.objects.filter(email=email).count() if email_count > 0: raise forms.ValidationError('This email is already in use. Please select a different email!') return email def calc_age(self): dob = self.cleaned_data.get('date_of_birth') raise forms.ValidationError(int(dob)) … -
Possible bug in Django in selecting a pandas DataFrame?
I am creating a Django project of which the code is rather complex. For that reason I split it into several files which are called from models.py. But because the code is complex I would like to run the code stand-alone to debug it. I have a simple piece of code that looks like this: print('DF:\n', df) selection = df[df[sel_crit] >= sel_val] print('SELECTION\n', selection) In the examples below: sel_crit is "Coverage" and sel_val is 0.1. The value of df is (first print statement): DF: cpu Status Coverage Distance Lyapunov FractDim Missers Uninteresting Coefficients 28 0.067678 1.0 0.107931 95.987910 NaN 0.569875 0.0 0.0 IQLHUFOFBKCJGUSQGPJPTPNUDPMTPAU 304 0.124464 1.0 0.107508 93.144860 0.032726 NaN 0.0 0.0 IUMOUMOGSHJIIPPPCNCCOJLHQFPZHPU 1241 0.123443 1.0 0.107392 82.698345 26.796081 0.999999 0.0 0.0 ILGDKLOSWHPJIPPPCTBITJLLQLPLCUM 117 0.123463 1.0 0.106203 80.419825 -0.862029 0.602059 0.0 0.0 ILJEHSNGNHGGIJJLFNJPOBAUDQALHUM 386 0.131001 1.0 0.102985 73.330918 -3.630947 NaN 0.0 0.0 INTDEKECMIQPLKELOBHJHLREUDGKAMG 1117 0.125086 1.0 0.096597 79.500703 -0.793354 0.371611 0.0 0.0 IKHRKQQPAEGLLCBFFPCQPROBUMLGCOH 797 0.123657 1.0 0.094546 97.020646 0.828907 1.204119 0.0 0.0 IGXYLPLFCHSPMHHDMFCREMMPAWPUFQL 356 0.126138 1.0 0.091071 88.329201 -0.361238 1.414972 0.0 0.0 IKKQLLHCNLGLLSHLEPIQCIGKKDHTFBH 675 0.123957 1.0 0.072746 103.955944 15.489624 1.531477 0.0 0.0 IQUAUIFLCCQPZKHYIGLOHMHSONMXCPW 182 0.123799 1.0 0.065901 63.458365 -0.523814 1.903088 0.0 0.0 ITMBUJLNUOMGTVNDPNJVOCNUDSMTMIU The results produced by the Djando runserver: … -
Django relay graphql order by created date
How to query a model as order by created date in django graphene-relay class CategoryNode(DjangoObjectType): class Meta: model = Category filter_fields = ['name', 'ingredients', 'created_at'] interfaces = (relay.Node, ) class Query(graphene.ObjectType): category = relay.Node.Field(CategoryNode) all_categories = DjangoFilterConnectionField(CategoryNode) -
Dynamic Model Django - similar repeated items
I am working on building a quote generation tool with django and trying to determine the best way to build the model(s). For example, a quote could have n number of different items to be worked on: driveway1, driveway2, sidewalk, wall, fence, etc, etc. Each of these different items will have a similar calculation: length x width or flat fee My initial thought was to build a model to house all of the items and the two calculations: class item(models.Model): item = models.CharField(max_length=250) length = models.FloatField(blank=True, null=True) width = models.FloatField(blank=True, null=True) flat_fee = models.FloatField(blank=True, null=True) Example Submissions: Form 1: driveway, 50,50, null Form 2: driveway, 60,40, null | sidewalk, 10, 10, null How could I store these two results without pre-defining the schema as it could change with every form submission? Is this a good use-case for NoSQL?