Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Couldn't Make Django Talk with Postgres in k8s
I have a deployment of simple django app in minikube. It has two containers one for django app and one for postgres db. It is working with docker-compose, but couldn't make it work in minikube k8s cluster. When I opened a terminal to the container and ping the service it wasn't succesful. I didn't find what causes this communication error. DATABASES part in settings.py in django project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } Deployment file: apiVersion: apps/v1 kind: Deployment metadata: name: notejam-deployment labels: app: notejam-app spec: selector: matchLabels: app: notejam-app template: metadata: labels: app: notejam-app spec: volumes: - name: postgres-pvc persistentVolumeClaim: claimName: postgres-pvc containers: - name: notejam image: notejam_k8s imagePullPolicy: Never resources: limits: memory: "128Mi" cpu: "500m" ports: - containerPort: 8000 - name: postgres-db image: postgres imagePullPolicy: Never ports: - containerPort: 5432 resources: limits: memory: "128Mi" cpu: "500m" env: - name: POSTGRES_USERNAME valueFrom: configMapKeyRef: name: postgres-configmap key: postgres-username - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgres-secret key: postgres-password - name: POSTGRES_DB valueFrom: configMapKeyRef: name: postgres-configmap key: postgres-db volumeMounts: - mountPath: /notejam-db name: postgres-pvc --- apiVersion: v1 kind: Service metadata: name: db spec: selector: app: notejam-app ports: - port: … -
¿Is it good practice to add migrations files to the repository?
I am using Django Framework to create my applications and I am uploading them to GitHub. I have like a "history" of migrations files and they are all there, Is it good practice to upload all migrations files to GitHub or do they need to be deleted? Thank you! -
I have two for loops in Jinja. (Django Project) I want to save the forloop.counter for the first loop to a variable and use in the secodn loop
I can't get the correct loop counter variable to save - I want a similar functionality to the enumerate in python, or just a way to store my variables for the next for loop. {% for boards, value_dict in my_dict.items %} **{{ forloop.counter }}** <---- gets the correct loop index I need {% for mode, platform_dict in value_dict.items %} // I have no way of saving the above value, if I call forloop.counter in this line it gets the counter for the wrong forloop **// I need to use the index above in this line.** {% for mode, platform_dict in value_dict.items %} **// I also need the same variable here** {% endfor %} {% endfor %} {% endfor %} What I tried using : {% with counter=forloop.counter %} (in first loop set this) {% with forloop.counter as counter %} {set counter = {{forloopcounter}} (in first loop set this) Using loop.index Using forloop.parent.count This seems to be a very simple thing I want to do yet I can seem to find the right syntax to do it. Also using the -
Create Django Serializer with default fields in Meta and query params
I'm trying to write a Serializer that would take dynamic fields and add them to the restricted number of fields specified in Meta, but it seems that there's no method to "add back" a field to the serializer once it's been created. Dynamic Fields per Django documentation class DynamicFieldsModelSerializer(ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) class BldgLocationAndFilters(DynamicFieldsModelSerializer): latitude = fields.FloatField(source='lat_016_decimal') longitude = fields.FloatField(source='long_017_decimal') class Meta: model = Bldg fields = ('latitude', 'longitude') I'd like to do something that would modify the DynamicFieldsModelSerializer such that fields can be appended to the set that has already been filtered down, but it looks like the Meta fields override everything such that nothing can be added back (fields can only be removed Pseudocode of desired behavior: class DynamicFieldsUnionModelSerializer(ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument … -
Django request.method in class View
I have a simple question as in title, how to use request.method inside class view. I have form there and I would like to play with her. class ShopDetailView(DetailView): model = Item template_name = 'shop/detail.html' context_object_name = 'item' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = CommentCreationForm() context['comments'] = Comments.objects.all() context['profile'] = Profile.objects.all() return context if request.method == 'POST' -
show informations from a table, django
(Sorry for asking but I'm a beginner on django) I'm looking for to show informations from my database 'profile' but I don't find how to make that... There is two functionality to show on my 'infos.html' : the one part is for user's informations like the mail and birthday, the second part is for the favourite items who have been add by the user. #views.py -- post from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse, Http404 from django.db import models from .models import Post from django.utils import timezone from django.contrib import messages from django.contrib.auth import logout from django.urls import reverse, reverse_lazy from .forms import PostForm from django.contrib.auth.decorators import login_required import datetime def index(request): posts = Post.objects.order_by('-id') posts_number = posts.count() context = { 'posts' : posts, 'posts_number': posts_number, } return render(request, 'blog/pages/index.html', context) def details(request, pk): post = Post.objects.get(pk=pk) context = { 'post': post, } return render(request, 'blog/pages/details.html', context) @login_required def new_post(request): if request.method == 'POST': form =PostForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.author= request.user form.save() return redirect('new_post') else: form = PostForm() context ={ 'form' : form, } return render(request, 'blog/pages/new_post.html', context) @login_required def update_post(request,pk): post = Post.objects.get(pk=pk) if post.author == request.user : if request.method == 'POST': … -
How do i run some python code in the background
So I'm making a website using Django, and there is some code that I have set up to run every hour, however when I call this as a function in views.py it doesn't load the web page until the function has finished which isn't ideal for my website, I want it to be a background process which occurs outside my views file. -
How to change a value of HttpRequest.body in django?
I am getting a HttpRequest object in my view function. I want to change a particular key-value of that request. Currently I am doing this - def myview(request): request._body['key1'] = 'value1' # where 'key1' already exists in request body ... But this is giving an error: TypeError: 'bytes' object does not support item assignment -
What python http server to use?
I'm looking to build a python script that will listen to requests on mysite.com/@username then will get the username and internally fetch this user's pictures from instagram, then do some processing on the images, save them locally so they don't have to be fetched again and return the urls of these new processed images. I have a basic idea of how to do it but I'm not sure if I should use something like Django, Flask or just simply http-server. This is something only I'll use so that's why I wonder if I might be overthinking it.