Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UML diagrams to Django Models
I am a little bit confused about converting uml diagrams to django models. so I have decided to take help from you guys. so I am attaching a uml diagram so that you can guide me on how to convert it into django models. Your help would be ppreciated.enter image description here -
Do not saving when either of the 2 fields are not unique (Updated question)
I have the following codes models.py: class Device(models.Model): hostname = models.CharField(max_length=50, unique=True) ipaddr = models.GenericIPAddressField(protocol='ipv4', default='0.0.0.0') date_added = models.DateTimeField(default=timezone.now) def __str__(self): return self.hostname class DeviceDetail(models.Model): SUBNET_CHOICES = ( ('16','16'), ('17', '17'), ('18','18'), ('19','19'), ('20','20'), ('21', '21'), ('22', '22'), ('23', '23'), ('24', '24'), ('25', '25'), ('26', '26'), ('27', '27'), ('28', '28'), ('29', '29'), ('30', '30'), ) DEV_MODS =( ('Catalyst 9606R', 'Catalyst 9606R'), ('C9300L-48T-4X', 'C9300L-48T-4X') ) hostname = models.CharField(max_length=50) mgt_interface = models.CharField(max_length=50) mgt_ip_addr = models.GenericIPAddressField(protocol='ipv4', unique=True) subnetmask = models.CharField(max_length=2, choices = SUBNET_CHOICES) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) dev_mod=models.CharField(max_length=50, choices = DEV_MODS) ##device_model replacement DD2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables def __str__(self): return self.hostname class DeviceInterface(models.Model): MODULE_ID_CHOICES = ( ('TenGigabitEthernet','TenGigabitEthernet'), ('FortyGigabitEthernet','FortyGigabitEthernet'), ('GigabitEthernet','GigabitEthernet'), ('Ethernet','Ethernet'), ) moduletype = models.CharField(max_length = 50,choices = MODULE_ID_CHOICES) firstportid = models.CharField(max_length=50) lastportid = models.CharField(max_length=50) I2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables def __str__(self): return self.moduletype forms.py: class DeviceForm(ModelForm): class Meta: model= Device fields= ['hostname'] labels = { "hostname": "Hostname", } class DeviceDetailForm(ModelForm): class Meta: model= DeviceDetail fields= ['hostname', 'mgt_interface', 'mgt_ip_addr', 'subnetmask', 'ssh_id', 'ssh_pwd', 'enable_secret', 'dev_mod'] labels = { "mgt_ip_addr": "Management IP Address", } widgets = { 'enable_secret': forms.PasswordInput(), 'ssh_pwd': forms.PasswordInput() } def clean_hostname(self): hostname = self.cleaned_data['hostname'] if … -
How display custom error message above a model field in Django admin when a JSONSchemaValidationError occured?
I'm using JSONSchema validation but when an exception occurred it throw a validation error that will display the Validation Error message on a separate page. But I want to display an error message on the admin page next to that field displaying why the value is not saved. -
How to write create() function in DRF serializer for model with a many-to-many field by passing data through axios, and vue
I have vue at the frontend and I'm using axios to post user input to api. I have a Class model and a Student Model. In Student Model, I have a field named "classes" as many to many field. users will be able to input all the fields beside the class.id in the form(since I class.id can be retrieved using $router.params). I want to create the Student instance and add this class instance called clss to its relation. student.classes.add(clss). How am i supposed to implement the create() in serielizer class? I tied to come up with the following but it seems not working. class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ( "id", "classes", "studentID", "lastName", "firstName", "gender", "dob", "ssn", "tel", "address", "email", "userName", "acctPass", "note" ) def create(self, validated_data): clss = self.request.query_params['class_id'] student = Student.objects.create(**validated_data) student.classes.add(clss) student.save() return student in AddStudent Vue i have the following: xport default { name: 'AddStudent', data(){ return { clss:{}, student:{} } }, async mounted(){ await this.getClass() }, methods:{ getClass(){ const classID = this.$route.params.id axios .get(`/api/v1/classes/${classID}`) .then(response => { this.clss = response.data }) .catch(error => { console.log(JSON.stringify(error)) }) }, submitForm(){ const classID = this.$route.params.id axios .post("/api/v1/students/", this.student, {params: {class_id: classID, } } ) … -
HTML format on Django text field model
I want to create a blog. I want to create blog content in admin panel and render the blog content with HTML format. models.py class Blog(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_created = models.DateField(auto_now_add=True) def __str__(self): return self.title In admin panel : Create blog content with HTML format in admin In template: {% extends 'base.html' %} {% block content %} <h1>{{ blog.title }}</h1> <p>{{ blog.content }}</p> {% endblock content %} Is there any template tags, model field, or anything to do this? -
Modal window retriving dynamic data by Django
I need a modal window that dynamically show post content. What i already have done: a post list which has title and some meta data. Some modal code when i click the title, it shows up. This is what i get so far. enter image description here But it is dead data, it is not retriving from database according to the pk of the post i clicked, which means i need to pass at least the prymary key of that post and get it show up in the modal window. -
Fields values do not display after detect error in form Django
The values filled in the form are not being shown after issuing a validation error. {{ object }} It is not shown. Form class EmpresaForm(forms.ModelForm): class Meta: model = models.Empresa fields = [ "fantasia", "razao", "cnpj", "seguimento" ] View class EmpresaCreateView(generic.CreateView): model = models.Empresa form_class = forms.EmpresaForm Template <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.errors}} <div class="form-group row"> <label class="col-sm-2 col-form-label" for="last_updated">last_updated: </label> <input class="form-control col-sm-10" id="last_updated" type="datetime-local" name="last_updated" value="{{ object.last_updated }}" disabled> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label" for="created">created: </label> <input class="form-control col-sm-10" id="created" type="datetime-local" name="created" value="{{ object.created }}" disabled> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label" for="fantasia">fantasia: </label> <input class="form-control col-sm-10" id="fantasia" type="text" name="fantasia" value="{{ object.fantasia }}"> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label" for="razao">razao: </label> <input class="form-control col-sm-10" id="razao" type="text" name="razao" value="{{ object.razao }}"> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label" for="cnpj">cnpj: </label> <input class="form-control col-sm-10" id="cnpj" type="text" name="cnpj" value="{{ object.cnpj }}"> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label" for="seguimento">seguimento: </label> <input class="form-control col-sm-10" id="seguimento" type="text" name="seguimento" value="{{ object.seguimento }}"> </div> <input type="submit" value="Save" class="btn btn-primary"> </form> -
Django rest framework: read only views and serializers
As answers to this question suggested, to make a model readonly through drf, there're serializer level and view level solutions. Is it sufficient to make only one level readonly? readonly serializer readonly serializer + readonly view readonly view -
Django single query to count & use data on for loop?
I need to display total count & also use the queryset to loop on the template ! But the thing is its causing two queries to do this, is there any efficient way to manage this on single query ? data = Data.objects.filter(pk=pk) count = data.count // 1st query and then using data to iterate over loop on template // this makes second query Is there any other best way to do the same thing or it needs these two queries for sure ? -
How to query a relationship that spans three models in Django?
I have the following models: class Station(models.Model): name = models.CharField(max_length=166) number = models.CharField(max_length=2) class Exercise(models.Model): exercice = models.CharField(max_length=166) series = models.CharField(max_length=2) reps = models.CharField(max_length=2) station = models.ForeignKey(Station) class Workout(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE) day = models.CharField(max_length=1, verbose_name="Dia") exercises = models.ManyToManyField(Exercise) I then created a table that presents the exercises for each workout using the following view: def planodet(request, id): plan = Workout.objects.get(id=id) exercises = plan.exercises.values() But when I loop through exercises I can't fetch the Station name. How can I access this? I've tried Station.objects.filter(name=exercises[0]) But to no success. -
attribute error, 'tuple' object has no attribute '_meta'
i try my first django project. it appear such error AttributeError: 'tuple' object has no attribute '_meta' here is my views.py from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Post from .forms import PostForm # Create your views here. def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) def post_new(request): form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) here is my urls.py from django.urls import path from . import views urlpatterns =[ path('', views.post_list, name='post_list'), path('post/<int:pk>/', views.post_detail, name='post_detail'), path('post/new/', views.post_new, name='post_new'), ] and here my forms.py from django.forms.models import fields_for_model from .models import Post class PostForm(forms.ModelForm): class Meta: model = Postfields = ('title', 'text',) fields = '__all__' when i exe manage.py runserver, i hit that error. the first error is modelform without either the 'fields' attribute or the 'exclude' i repair it with added fields = '__all__' in forms.py any idea? i am using python 3 and django 2.2.4 thanks -
Django DRF: ModelViewSet: How to show some foreign key properties along with id
## MODELS class Animal(models.Model): name = models.CharField(max_length=200, unique=True) number_of_legs = models.CharField(max_length=200, unique=True) ... (there are several other properties here) class Breed(models.Model): name = models.CharField( max_length=200, unique=True, ) animal = models.ForeignKey( "Animal", on_delete=models.CASCADE, ) ... (there are several other properties here) class Pet(models.Model): name = models.CharField(max_length=200) breed = models.ForeignKey( "Breed", on_delete=models.CASCADE, ) ### SERIALIZERS class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = "__all__" class BreedSerializer(serializers.ModelSerializer): class Meta: model = Breed fields = "__all__" class PetSerializer(serializers.ModelSerializer): class Meta: model = Pet fields = "__all__" ## ModelViewset class PetViewSet(viewsets.ModelViewSet): queryset = Pet.objects.all() serializer_class = PetSerializer When I am trying to GET the list of pets I want something like this [{ "id": 1, "name": "rexy", "breed": 2, <-- foriengkey id --> HERE I ALSO WANT "breed name" <-- I dont want other properties of breed "animal name" <-- I dont want other properties of animal }] -
ModuleNotFoundError: No module named 'django.contrib.wagtail'
We are working on a Django project and wanting to upgrade the packages to the latest version. To begin with, we tried installing all the packages related to the project as mentioned in the requirements.txt. While installing the packages mentioned in the requirements.txt file, some of packages required upgrades. So, we upgraded them accordingly, please find the latest packages installed in the project under requirements_new.txt (File generated using pip freeze > requirements_new.txt). We were able to successfully install all the packages. However, when we execute python manage.py makemigrations, we are getting the below error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "D:\GA\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "D:\GA\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "D:\GA\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\GA\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "D:\GA\venv\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\sweth\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.contrib.wagtail' Please find below the packages in requirements_new.txt anyascii==0.2.0 asgiref==3.4.1 atomicwrites==1.3.0 backports.zoneinfo==0.2.1 beautifulsoup4==4.9.3 bleach==3.1.4 boto3==1.11.10 botocore==1.14.10 certifi==2021.5.30 cffi==1.13.2 chardet==3.0.4 charset-normalizer==2.0.4 cssselect2==0.2.2 defusedxml==0.6.0 … -
i need a help in this django error i am new to django
This is the error i am having :- ImproperlyConfigured at /attendanceattendance/add AddAttendance is missing a QuerySet. Define AddAttendance.model, AddAttendance.queryset, or override AddAttendance.get_queryset(). This is my models.py class StudentAttendance(models.Model): StudentName = models.CharField(max_length=150) StudentRoll = models.CharField(max_length=100) lecturesAttended = models.IntegerField(null=True) TotalLectures = models.IntegerField(null=True) slug = models.SlugField(allow_unicode=True,null = True) def __str__(self): return self.StudentName def save(self,*args,**Kwargs): self.slug = slugify(self.StudentName) super().save(*args,**Kwargs) def get_absolute_url(self): return reverse("home") class Meta(): ordering = ['StudentName'] This is my view class AddAttendance(generic.CreateView,LoginRequiredMixin): form_model = forms.AttendanceForm success_url = reverse_lazy('home') template_name = 'attendance/attendance.html' This is my urls from django.conf.urls import url from . import views app_name = 'attendance' urlpatterns = [ url(r'^attendance/add',views.AddAttendance.as_view(),name='attend') ] enter image description here -
Django won't upload and save document
Can you see is there any problem? I don't have any errors, everything is showing but when I upload document, nothing happens, document is not uploaded. Everything seems as it should be, but something I missed, why won't upload document? my_app/forms.py class UploadFileForm(forms.Form): file = forms.FileField() my_app/hendle_file.py def handle_uploaded_file(f): with open('my_app/static/upload/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) my_app/views.py from .forms import UploadFileForm from .handle_file import handle_uploaded_file def upload_file(request): form = UploadFileForm() if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): print(form.cleaned_data) handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('success') else: form = UploadFileForm() return render(request, 'my_app/uploadfile.html', {'form': form}) my_app/template/my_app/uploadfile.html {% extends "my_app/base.html" %} {% block content %} <form method="post"> {% csrf_token %} <h1>Upload your document!</h1> {{ form.as_p }} <input type="submit" type="button" value="Upload" </form> {% endblock content %} -
How to get both pk and a form input on submit in Django
Am using Django to create a system that records available stock of a shop, and records the sales made. I have a 'Sell Item' button on every available item, so that the seller uses the button to record that a sale was made. So am requesting the pk(through the url) of the item on which the button was clicked(to know which item is being sold), and I also have a form where the seller will input the quantity being sold, so that I get how many items are being sold(Am trying to get this using the GET method). But am getting errors that quantity is None since am unable to get the quantity. This is my template: <td> <form action="{% url 'stock:sell' pk=item.pk%}" method="GET"> <input type="number" id="quantity" value="1" size="5"> {% csrf_token %} <button type="submit" name="submit">Sell</button> </form> </td> This is my url: path('sell/<pk>/', sell, name='sell'), And this is my views: def sell(request, pk): if request.method == 'GET': quantity_sold = request.GET.get('quantity') item = Item.objects.get(id=pk) if quantity_sold > int(item.quantity): messages.danger(request, "Not enough stock to sell that quantity!") else: item.quantity -= quantity item.save() return HttpResponseRedirect(reverse('stock:show_stock')) Am getting the quantity to make sure that only available quantity can be sold, and then to update to … -
Issue pulling data from xml with etree.ElementTree
I'm working with JMDict (https://www.edrdg.org/jmdict/j_jmdict.html). Here is a little example of the data I'm having trouble with: <entry> <ent_seq>1265070</ent_seq> <k_ele> <keb>古い</keb> <ke_pri>ichi1</ke_pri> <ke_pri>news1</ke_pri> <ke_pri>nf16</ke_pri> </k_ele> <k_ele> <keb>故い</keb> </k_ele> <k_ele> <keb>旧い</keb> </k_ele> <r_ele> <reb>ふるい</reb> <re_pri>ichi1</re_pri> <re_pri>news1</re_pri> <re_pri>nf16</re_pri> </r_ele> <sense> <pos>&adj-i;</pos> <s_inf>of things, not people</s_inf> <gloss lang="eng">old</gloss> <gloss lang="eng">aged</gloss> <gloss lang="eng">ancient</gloss> <gloss lang="eng">antiquated</gloss> <gloss lang="eng">antique</gloss> <gloss lang="eng">timeworn</gloss> </sense> <sense> <pos>&adj-i;</pos> <gloss lang="eng">long</gloss> <gloss lang="eng">since long ago</gloss> <gloss lang="eng">time-honored</gloss> </sense> <sense> <pos>&adj-i;</pos> <gloss lang="eng">of the distant past</gloss> <gloss lang="eng">long-ago</gloss> </sense> <sense> <pos>&adj-i;</pos> <gloss lang="eng">stale</gloss> <gloss lang="eng">threadbare</gloss> <gloss lang="eng">hackneyed</gloss> <gloss lang="eng">corny</gloss> </sense> <sense> <pos>&adj-i;</pos> <gloss lang="eng">old-fashioned</gloss> <gloss lang="eng">outmoded</gloss> <gloss lang="eng">out-of-date</gloss> </sense> <sense> <gloss lang="dut">oud</gloss> </sense> <sense> <gloss lang="dut">aloud</gloss> <gloss lang="dut">verouderd</gloss> <gloss lang="dut">oubollig</gloss> <gloss lang="dut">gedateerd</gloss> <gloss lang="dut">ouderwets</gloss> <gloss lang="dut">oudmodisch</gloss> <gloss lang="dut">archaïsch</gloss> <gloss lang="dut">antiek</gloss> <gloss lang="dut">{i.h.b.} afgezaagd</gloss> </sense> <sense> <gloss lang="dut">niet vers</gloss> <gloss lang="dut">onfris</gloss> <gloss lang="dut">belegen</gloss> <gloss lang="dut">oud</gloss> <gloss lang="dut">oudbakken</gloss> <gloss lang="dut">verschaald</gloss> <gloss lang="dut">muf</gloss> </sense> <sense> <gloss lang="dut">gebruikt</gloss> <gloss lang="dut">afgewerkt</gloss> <gloss lang="dut">sleets</gloss> <gloss lang="dut">versleten</gloss> </sense> <sense> <gloss lang="fre">vieux (sauf pour les personnes)</gloss> <gloss lang="fre">âgé</gloss> <gloss lang="fre">ancien</gloss> <gloss lang="fre">antique</gloss> <gloss lang="fre">vieilli</gloss> <gloss lang="fre">vieillot</gloss> <gloss lang="fre">caduque</gloss> <gloss lang="fre">démodé</gloss> <gloss lang="fre">obsolète</gloss> <gloss lang="fre">passé</gloss> <gloss lang="fre">vicié</gloss> <gloss lang="fre">usé</gloss> </sense> <sense> <gloss lang="ger">alt</gloss> <gloss lang="ger">altertümlich</gloss> </sense> <sense> <gloss lang="ger">langjährig</gloss> <gloss lang="ger">sich über lange Zeit erstreckend</gloss> </sense> <sense> <gloss lang="ger">altehrwürdig</gloss> <gloss lang="ger">althergebracht</gloss> … -
robot with django not working in setting up with module not found
I am trying to set up robot framework on django application. I am testing on a skeleton applciation. Following these instructions https://github.com/kitconcept/robotframework-djangolibrary i get error % robot tests/test.robot [ ERROR ] Error in file '/Users/user/hci/pipeline/app/tests/test.robot' on line 13: Importing library 'MIDDLEWARE_CLASSES' failed: ModuleNotFoundError: No module named 'MIDDLEWARE_CLASSES' Traceback (most recent call last): None PYTHONPATH: /Users/user/.pyenv/versions/3.7.2/bin /Users/user/.pyenv/versions/3.7.2/lib/python37.zip /Users/user/.pyenv/versions/3.7.2/lib/python3.7 /Users/user/.pyenv/versions/3.7.2/lib/python3.7/lib-dynload /Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages ============================================================================== Test :: Django Robot Tests ============================================================================== Scenario: As a visitor I can visit the django default page | FAIL | Parent suite setup failed: No keyword with name 'Start Django' found. ------------------------------------------------------------------------------ Test :: Django Robot Tests | FAIL | Suite setup failed: No keyword with name 'Start Django' found. Also suite teardown failed: No keyword with name 'Stop Django' found. 1 test, 0 passed, 1 failed ============================================================================== Output: /Users/user/hci/pipeline/app/output.xml Log: /Users/user/hci/pipeline/app/log.html Report: /Users/user/hci/pipeline/app/report.html This is the content of my files In settings.py I have MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'DjangoLibrary.middleware.AutologinAuthenticationMiddleware', 'DjangoLibrary.middleware.FactoryBoyMiddleware', 'DjangoLibrary.middleware.QuerySetMiddleware', ] MIDDLEWARE_CLASSES = ( 'django.contrib.auth.middleware.AuthenticationMiddleware', 'DjangoLibrary.middleware.AutologinAuthenticationMiddleware', 'DjangoLibrary.middleware.FactoryBoyMiddleware', 'DjangoLibrary.middleware.QuerySetMiddleware', ) In test.robot i have *** Variables *** ${HOSTNAME} 127.0.0.1 ${PORT} 55001 ${SERVER} http://${HOSTNAME}:${PORT}/ ${BROWSER} firefox *** Settings *** Documentation Django Robot Tests Library Selenium2Library timeout=10 implicit_wait=0 Library MIDDLEWARE_CLASSES ${HOSTNAME} ${PORT} path=pipeline/pipeline manage=pipeline/manage.py settings=pipeline.settings … -
Can anyone guide me to build a website monitoring web Application using django?
Website monitoring web Application means, i give it a url of any website(from server site) and it return me the status_code(on server site) of that website, whether it is ok(200) or it has downtime (any error) and also alert me through email. -
How do you selectively migrate Django models?
Given any standard Django models.py file, how can you tell Django to include / exclude certain models conditionally (e.g. based on variables in the settings.py module) when running python manage.py makemigrations [app_name]? -
Sending Javascript fetch to Django
I am struggling to send fetched json to Django, not sure if I am doing it in the correct way. I am trying to fetch API response with GET, then inside the fetch send each element to Django with POST, to populate my database (views and everything are already set up). API search request provides multiple Json responses, so I am trying to loop it. My code is as following: s_button.addEventListener('click', function(e){ var x = document.querySelector('#search'); var searching = "&search=" + x.value // fetches by search fetch(website + searching, requestOptions) .then(response => response.json()) .then(result => { var list = result; for (let i = 1; i < 10; i++) { console.log(result.results[i].name) //here it changes table based on id from html htmlname = "number" + i.toString(); // sets name to fetched name and id to fetched id document.getElementsByClassName(htmlname)[0].innerHTML = result.results[i].name; document.getElementsByClassName(htmlname)[0].id = result.results[i].id; console.log("REQUEST:") //this suppose to send to POST but it gives error! $(document).ready(function() { $.ajax({ method: 'POST', url: '', data: {'yourJavaScriptArrayKey': result.results[i], 'csrfmiddlewaretoken': '{{ csrf_token }}'}, 'dataType': 'json', success: function (data) { //this gets called when server returns an OK response console.log("it worked!"); }, error: function (data) { console.log("it didnt work"); } }); }); } id = result.results[0] }) … -
how to calculate date after 8 months from delivery_date?
I want to make a function that returns the expiration date. this is the field to calculate from? delivery_date = models.DateTimeField(auto_now_add=True) -
How do I get "the least frequent" item on a table by filtering with data from another table
I'm trying to build an audio database and these are some of the models I'm using: class State(models.Model): abbreviation = models.CharField(max_length=2) ... class City(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE) ... class Sentence(models.Model): text = models.CharField(max_length=255) ... class Speaker(models.Model): birth_city = models.ForeignKey( City, on_delete=models.CASCADE, related_name="birth_city" ) ... class Record(models.Model): sentence = models.ForeignKey(Sentence, on_delete=models.CASCADE) speaker = models.ForeignKey(Speaker, on_delete=models.CASCADE) ... and I'm trying to setup a ViewSet so I can get an endpoint such as /sentence/?state=STATE, where STATE is the State.abbreviation that would return me the least recorded sentence for that state. This is what I've got so far: class SentenceViewSet(viewsets.ModelViewSet): serializer_class = SentenceSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def get_queryset(self): queryset = Sentence.objects.all() state = self.request.query_params.get("state", None) if state is not None: # Get all records for this state records = Record.objects.filter( speaker__birth_city__state__abbreviation=state ) # Get sentence with the lowest number of records queryset = queryset.filter( id=records.values("sentence") .annotate(dcount=Count("id")) .order_by("dcount")[0]["sentence"] ) else: queryset = queryset.order_by("text") return queryset Unfortunately, this will only return sentences I have already recorded. How do I get around this? -
Upgrade PostgreSQL from version 9.6 to version 11 using Django 1.11 and Heroku
I have a monolithic application using Django 1.11 and Postgres 9.6 deployed on Heroku, I'm using Heroku Postgres Instances. Heroku is asking to upgrade to newer versions because Postgres 9.6 will be deprecated soon. I've tried 2 times to upgrade my production DB to version 10 and 11 and after deployed and connected to my application everything start going bad. Almost all query plans are taking a lot of time compared to the same plans in version 9.6, which is currently working very well. I've notices some errors due to pgbouncer connection after deployed with the new upgraded DB. pgbouncer cannot connect to serverSSL connection has been closed unexpectedly I'm using pgbouncer to handle DB connections on my application and also I'm using Heroku connection pool technology to deal connections on Postgres server too.I can see the detachment of the old pool and the attachment of the new one and seems to be working fine. Also, I've seen a bunch of SET operations taking almost 30 secs, not sure if it's just because everything starts to go so bad after the upgrade. Also even query plans with 1 step of INDEX call is taking almost 600 secs in a low … -
Cant handle DoesNotExist error with nested resources
I'm having trouble handling DoesNotExist error, Im using DRF and DRF-Nested-Routers and when I create a new Like object I need the Photo PK so I can add it to the Like object. I'm trying to catch the error that I get when the Photo with that PK doesn't exist. This is how I'm doing the creation of the Like in the serializer: def create(self, validated_data): # Get the photo pk from the view context (DRF-nested-routers) and # create the new like with the validated_data photo_pk = self.context['view'].kwargs["photo_pk"] try: photo = Photo.objects.get(id=photo_pk) except ObjectDoesNotExist: return Response(data={'detail': "The photo doesn't exist."}, status=status.HTTP_404_NOT_FOUND) validated_data["photo"] = photo like, created = Like.objects.get_or_create(**validated_data) if created: photo.total_likes += 1 photo.save() return like The response I get with this is: {'user': 'my username here'} I also tried with except Photo.DoesNotExist but it gives the same result.