Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Pass Model objects to context_processors
As a new developer to Django, I am running into an issue of trying to pass a model's object list to a global variable accessible on any template, within any app. settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(PROJECT_ROOT, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'myapp.site_context.site_context_processor', ], }, }, ] site_context.py from .apps.events.models import Event def site_context_processor(request): ctx = {} ctx['current_year'] = time.strftime("%Y") ctx['events'] = Event.objects.active()[0] return ctx I am running into an issue of an app_label missing on the Events model, but when I add this, I get conflicting apps in the settings.py Model class myapp.apps.events.models.Event doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. when settings.py looks like INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'directory', 'events', 'utilities', 'filebrowser', ] but when I add the app via myapp.apps.Events I get RuntimeError: Conflicting 'event' models in application 'events': <class 'events.models.Event'> and <class 'myapp.apps.events.models.Event'>. Not sure where to go from here. Any help would be greatly apperciated. -
How could I translate static data coming from JSon files in Django?
I have a json file with a long list of geographic locations [ { "id": 1, "name": "Afghanistan", "iso3": "AFG", "iso2": "AF", "phone_code": "93", "capital": "Kabul", "currency": "AFN", "currency_symbol": "؋", "tld": ".af", "native": "افغانستان", "region": "Asia", "subregion": "Southern Asia", "timezones": [ { "zoneName": "Asia\/Kabul", "gmtOffset": 16200, "gmtOffsetName": "UTC+04:30", "abbreviation": "AFT", "tzName": "Afghanistan Time" } ], "latitude": "33.00000000", "longitude": "65.00000000", "emoji": "🇦🇫", "emojiU": "U+1F1E6 U+1F1EB", "states": [ { "id": 3901, "name": "Badakhshan", "state_code": "BDS", "cities": [ { "id": 52, "name": "Ashkāsham", "latitude": "36.68333000", "longitude": "71.53333000" }, ....... /* very long list */ This file is loaded in Django forms when country/state/city dropdown lists are needed. The problem is that I want to translate at least the country names to other languages. Even if I was allowed to use {% trans "Country_name" %} in my JSon file it wouldn't be very practical. Is there a faster way to do so? For example making this in forms.py doesn't work: from django.utils.translation import gettext_lazy as _ # ... def get_country(): filepath = 'myproj/static/data/countries_states_cities.json' all_data = readJson(filepath) all_countries = [('----', _("--- Select a Country ---"))] for x in all_data: y = (x['name'], _(x['name'])) all_countries.append(y) return all_countries "--- Select a Country ---" will be translated but … -
Python Raw Recursive Query Convert
cursor.execute("WITH recursive subordinates AS (SELECT 1 as id FROM NODES WHERE node_id ='" + str(document_node_edit) + "' UNION ALL SELECT e.* FROM NODES e INNER JOIN subordinates s ON s.parent_node::text = e.node_id::text)SELECT s.short_code, s.node_type FROM subordinates s where s.location_id='" + str(location) + "' and s.node_type=1") -
How to create one to one field with Django for existing table?
We already have a model, let's say, Product. And we want to extend it into 'one to one relationship', let's say, ProductDetails. How do it in such way, that for each existing row of Product model row ProductDetails is created automatically? with some default vaules. Does Django provide such tool? The task seems pretty regular for me, but I can't find any native solution. -
How to customise message in send_mail in django
I'm trying to customise the message which I want to send to a gmail, like you may have seen some emails having nice layout, buttons and images. I want customise my message like that. But I'm not getting how to do it in django. Can anyone guide me how to do it? I'd appreciate some suggestions. Thank you. -
How do I fix AttributeError: type object 'Book' has no attribute 'published_objects' on django_3.2
I am trying to create a custom model manager by modifying an already existing queryset. After adding the custom manager to my models.py file, models.py from django.db import models from django.db.models.fields import DateField from django.utils import timezone, tree from django.contrib.auth.models import User class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Book(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) author = models.CharField(max_length=100) slug = models.SlugField( max_length=250, unique_for_date='uploaded_on') uploaded_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='book_posts') body = models.TextField() publish = models.DateField() uploaded_on = models.DateTimeField(default=timezone.now) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.CharField( max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published_objects = PublishedManager() class Meta: ordering = ('-category', ) def __str__(self): return self.title``` If I use the python manage.py shell to test I was able to retrieve all books using Book.objects.all() >>> Book.objects.all() <QuerySet [<Book: 48 Laws of Power>, <Book: The China Card>, <Book: Rich Dad, Poor Dad>]>``` But when trying to retrieve using my custom model, the is my following result >>> Book.published_objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: type object 'Book' has no attribute 'published_objects'``` How do I fix this error please, since i was following the original Django Documentations? -
Does the sync_to_async decorator really make django requests faster?
asgiref module has sync_to_async and async_to_sync function and decorator. I want to know if using sync_to_async this decorator can really make django requests faster,code like this: @csrf_exempt @sync_to_async def get_data(request): user_obj_qs = User.objects.all() user_list = [{'name': user_obj.first_name} for user_obj in user_obj_qs] return JsonResponse(user_list, safe=False) -
How to implements DataTable in a Django Project?
I'm new in Django framework and I'm trying to implement datatable into my project. I read the documentation of Django and Datatables and implemented exactly as stated, but somehow the datatable does not showing in the template and I don't know why. home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Django Project</title> {% include 'headers.html' %} {% include 'scripts.html' %} </head> <body class="hold-transition sidebar-mini layout-fixed"> <div class="wrapper"> {% include 'header.html' %} {% include 'sidebar.html' %} <div class="content-wrapper"> <section class="content-header"></section> <section class="content"> {% block content %} {% endblock content %} </section> </div> {% block javascript %} {% endblock %} {% include 'footer.html' %} <aside class="control-sidebar control-sidebar-dark"></aside> </div> </body> </html> headers.html {% load static %} <!-- DataTables --> <link rel="stylesheet" href="{% static 'lib/bootstrap-5.1.1-dist/css/bootstrap.min.css' %}" /> <link href="{% static 'lib/datatables-1.11.2/css/jquery.dataTables.min.css' %}" /> <link rel="stylesheet" href="{% static 'lib/datatables-1.11.2/css/dataTables.bootstrap4.min.css' %}" /> <link rel="stylesheet" href="{% static 'lib/datatables-1.11.2/css/responsive.bootstrap4.min.css' %}" /> <!-- Google Font: Source Sans Pro --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback" /> <!-- Font Awesome --> <link rel="stylesheet" href="{% static 'lib/adminlte-3.1.0/plugins/fontawesome-free/css/all.min.css' %}" /> <!-- overlayScrollbars --> <link rel="stylesheet" href="{% static 'lib/adminlte-3.1.0/plugins/overlayScrollbars/css/OverlayScrollbars.min.css' %}" /> <!-- Theme style --> <link rel="stylesheet" href="{% static 'lib/adminlte-3.1.0/css/adminlte.min.css' %}" /> scripts.html {% load static %} <script src="{% static … -
Limit number of images user can upload
I have a blog feature on my site, users can upload a single main image and multiple supporting images. The issue I am facing is I want to be able to limit the number of images a user can upload. I understand that I could use a for loop on it but if the user goes back later and adds more it would make the for loop useless. So I figured the best way to do this would be to add a field to the model that would count the number of images uploaded and then I can use an if statement to check if more than a said number of images have been uploaded. How would i go about getting the number of images and adding them to the post while it is being created. Or should I go about this a different way view @login_required def createPostView(request): currentUser = request.user postForm = PostForm() if request.method == 'POST': postForm = PostForm(request.POST, request.FILES) if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() for f in request.FILES.getlist('images'): test = PostImagesForm(request.POST, request.FILES) if test.is_valid(): instance = test.save(commit=False) instance.post_id = PostFormID.id instance.images = f instance.save() return HttpResponseRedirect("/") return render(request, 'blog/post_form.html', {'postForm': postForm, 'PostImagesForm':PostImagesForm}) -
Setting up gdal/osgeo Python library on Heroku
On my Windows machine, I have set up GDAL by following these instructions: downloading a wheel from Chris Gohkle's website and installing it using pip. pip install "C:/Users/andre/Downloads/GDAL-3.3.2-cp39-cp39-win_amd64.whl" This then gives me access to gdal like so: from osgeo import gdal How can I now re-create this for my Django App on Heroku? I have already followed the official Heroku instructions on installing GDAL with a buildpack. Although this is successful, I don't know how to install the osgeo library (and its gdal sub-module) on the remote Heroku machine. -
JavaScript only works on index.html in a Django web app
I recently started to integrate JavaScript into my Django projects. However, I am facing an issue: Whenever I try to animate an element by clicking on a button it works fine in the index.html but not on other templates that extend the layout.html. I am new to JavaScript so I couldn't trace back the roots of the problem. Here is my code: index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <script type="text/javascript" src="{% static 'js/script.js' %}"></script> <script type="text/javascript" src="{% static 'js/anime.min.js' %}"></script> <title>Meine Website</title> </head> <body> <div id="ball"></div> <button id="btnwow">Animieren</button> </body> </html> layout.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <script type="text/javascript" src="{% static 'js/script.js' %}"></script> <script type="text/javascript" src="{% static 'js/anime.min.js' %}"></script> <title>Layout</title> </head> <body> {% block body %} {% endblock %} </body> </html> thoughts.html {% extends 'website/layout.html' %} {% load static %} {% block body %} <div id="ball"></div> <button id="btnwow">Animieren</button> {% endblock %} script.js (in the same folder with anime.min.js) function animateStart(){ anime({ targets: '#topbar', translateY: [-500, 0], easing: 'easeInOutCirc', opacity: [.1, 1], … -
Question about Django. Assistance for the implementation of registration for the tournament
at the moment there are such models. class Team(models.Model): name = models.CharField('Название', max_length=35, unique=True) tag = models.CharField('Тег', max_length=16, unique=True) about = models.TextField('О команду', max_length=500, null=True, blank=True) logo = models.ImageField('Лого', upload_to="teams_logo/", null=True) game = models.ForeignKey( Game, verbose_name='игра', on_delete=models.SET_NULL, null=True, blank=True ) tournament = models.ManyToManyField('Tournaments', verbose_name='Турниры', blank=True) slug = models.SlugField(unique=True, blank=True, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("team_detail", kwargs={"slug": self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Team, self).save(*args, **kwargs) class Meta: verbose_name = "Команда" verbose_name_plural = "Команды" class Tournaments(models.Model): name = models.CharField('Название турнира', max_length=50) description = models.TextField('Описание турнира') prize = models.TextField('Призовой') game = models.ForeignKey( Game, verbose_name='Дисциплина', on_delete=models.CASCADE ) author = models.ForeignKey( User, verbose_name='пользователь', on_delete=models.CASCADE, blank=True, null=True ) teams = models.ManyToManyField( Team, verbose_name='Команда', blank=True ) image = models.ImageField('Лого турнира') max_teams = models.PositiveSmallIntegerField('Максимальное количество команд', default=0) count_registration_teams = models.PositiveSmallIntegerField('Количество зарегестрированных команд', default=0) start_date = models.DateTimeField("Дата начала") start_registration_date = models.DateTimeField("Начало регистрации") end_registration_date = models.DateTimeField("Конец регистрации") slug = models.SlugField(unique=True, blank=True, null=True) status = models.BooleanField('Статус активности', default=False) def __str__(self): return self.name def get_absolute_url(self): return reverse("tournament_detail", kwargs={"slug": self.slug}) def save(self, *args, **kwargs): self.slug = slugify(f'{self.name} - {self.game}') super(Tournaments, self).save(*args, **kwargs) def get_tournament(self): return self.tournamentregistration_set class Meta: verbose_name = "Турнир" verbose_name_plural = "Турниры" class TournamentRegistration(models.Model): tournaments = models.ForeignKey(Tournaments, on_delete=models.CASCADE) teams = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, blank=True) user … -
How to implement a generalized uniqueness DB constraint (A,B) and (B,A) in Django?
I want to check the database before an object is created with fields one='a' and two='b', and not create (throw an exception) if the database already has rows with fields one='b' and two='a' (reverse order). That is, guarantee that only one of (one, two) and (two, one) exists. It's like a generalized uniqueness constraint. I'm using Django 3.2. I see CheckConstraint supports a boolean Expression, and one type of expression is an aggregate. So I can imagine testing that the number of rows with (one, two) and (two, one) is at most 1. However, that sounds expensive, and I also don't see examples of how to use a Count in the CheckConstraint. Alternatively, I could implement a pre_save signal that issues a query. This seems better, as I'll have the data in hand to form the query. However, I don't see how to prevent the save using the pre_save signal. Does it have a return value I can use? I don't see that in the docs. I'm open to other ideas as well. -
Using django-hitcount in function-based view
I am trying to implement the logic used HitCountDetailView of django-hitcount module. I've successfully implemented it. My problem now is how can I make it count hit because now it counts one hit for each IP. Example. If I hit an object 5 times, it only counts the first one but I want it to count all. What do I need to overwrite? Below is my function def stats(request, watched_object): object = get_object_or_404(My_model, pk=watched_object.pk) context = {} hit_count = get_hitcount_model().objects.get_for_object(object) hits = hit_count.hits hitcontext = context['hitcount'] = {'pk': hit_count.pk} hit_count_response = HitCountMixin.hit_count(request, hit_count) if hit_count_response.hit_counted: hits = hits + 1 hitcontext['hit_counted'] = hit_count_response.hit_counted hitcontext['hit_message'] = hit_count_response.hit_message hitcontext['total_hits'] = hits return context -
Django filtering over multiple pages
I'm still new to Django and web development, sorry if the question is stupid. I currently have a search bar and a drop down list for a category, which then sends the query set to the results template. The result template also has filters to further refine The search, like price range, condition and for sorting. I was wondering what would be the best way to implement these filters without losing the query set from the previous page. views.py class ProductListView(ListView): model = Product template_name = "products/index.html" context_object_name = 'products' paginate_by = 10 class ProductSearch(ListView): model = Product template_name = "products/ad-list-view.html" context_object_name = "products" def get_context_data(self, **kwargs): context = super(ProductSearch, self).get_context_data(**kwargs) Product_list = super().get_queryset() context.update({ 'filter': ProductFilter( self.request.GET, queryset=Product_list) }) return context def get_queryset(self): search_query = '' if self.request.GET.get('search_query') or self.request.GET.get('category'): search_query = self.request.GET.get('search_query') option = self.request.GET.get('category') category = Category.objects.filter(Name__icontains=option) ducts = Product.objects.distinct().filter( Q(Product_name__icontains=search_query), category__in=category,) return ducts return search_query index.py <div class="container"> <div class="row justify-content-center"> <div class="col-lg-12 col-md-12 align-content-center"> <form method="GET" action="{% url 'Product-search' %}"> <div class="form-row"> <div class="form-group col-md-4"> <input type="text" class="form-control my-2 my-lg-1" id="inputtext4" placeholder="What are you looking for" name="search_query" value="{{search_query}}"> </div> <div class="form-group col-md-3"> <select name="featured" value= "{{featured}}" class="w-100 form-control mt-lg-1 mt-md-2"> <option value= null>Category</option> {% for … -
Debugging Django with VS Code inside a Docker container shuts down the container
I'm following this guide for debugging Django inside a Docker container using VS Code. The only difference I've made was changing ports to 8000 and host to 0.0.0.0 because my docker-compose has it like that. I have no idea why the web container shuts down when I run Django with a breakpoint inside a view because I'm don't really know where the problem is coming from. My only guess is from the vscode/launch.json file that is set up by the following: { "version": "0.2.0", "configurations": [ { "name": "Run Django", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}/app", "remoteRoot": "/usr/src/app" } ], "port": 8000, "host": "0.0.0.0", } ] } Any ideas why this is not working or where the problem is coming from? -
Using django url scheme with Javascript fetch API
I want to use django url scheme when working with fetch API, but it's not understood and i end up with an escaped URL. I followed this tutorial (in french sorry) in which the author achieve it very easily. Demonstrated here Example code : let url = "{% url 'myapp:search_user' %}" const request = new Request(url, {method: 'POST', body: formData}); fetch(request) .then(response => response.json()) .then(result => { console.log(result) }) Which ends up with a console error : POST http://127.0.0.1:8000/myapp/actions/%7B%%20url%20'myapp:search_user'%20%%7D 404 (Not found) Of course my URL is declared in url.py and works well when used in templates. If I replace "url" with relative path it's work well, but that's not django friendly. What I am missing ? -
"We're Sorry, Client not found" FreeIPA, Keycloak setup
I am setting up FreeIPA and Keycloak for user authentication for a django webapp. I have set up the client id and client secret in the .bashrc file and have included my path properly in django (the website loads, just not properly). The error displayed is "We're sorry, Client not found." I figure this may have something to do with setup. What should I do to fix this and make the ipa/keycloak login show the login fields? -
How to get uploaded file size in django
I am uploading a zip file through my form. How I can get the file size i.e in KB / MB so I can display it in my template. -
ValueError: Field 'song_id' expected a number but got 'Remove from Favourites '
ValueError: Field 'song_id' expected a number but got 'Remove from Favourites'. Django Music web App: I have added "Add to Favourite" feature, But Can't add "Remove from Favourite" feature Favourite.html <form action="/music/favourites" method="POST">{% csrf_token %} <input type="hidden" name="video_id" value="{{song.song_id}}"> <button type="submit" class="btn btn-outline-danger">Add to Favourite</button> </form> <form method="post"> {% csrf_token %} <input type="submit" class="btn btn-outline-danger" value="Remove from Favourites" name={{song.id}} > </form> #models.py class Song(models.Model): song_id = models.AutoField(primary_key= True) name = models.CharField(max_length= 2000) singer = models.CharField(max_length= 2000) tags = models.CharField(max_length= 100) image = models.ImageField(upload_to = 'docs') song = models.FileField(upload_to= 'docs') movie = models.CharField(max_length = 150, default = "None") def __str__(self): return self.name class Favourites(models.Model): watch_id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) video_id = models.CharField(max_length=10000000, default="") #Views.py def favourites(request): if request.method == "POST": user = request.user video_id = request.POST['video_id'] fav = Favourites.objects.filter(user=user) for i in fav: if video_id == i.video_id: message = "Your Video is Already Added" break else: favourites = Favourites(user=user, video_id=video_id) favourites.save() message = "Your Video is Succesfully Added" song = Song.objects.filter(song_id=video_id).first() return render(request, f"music/songpost.html", {'song': song, "message": message}) wl = Favourites.objects.filter(user=request.user) ids = [] for i in wl: ids.append(i.video_id) preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(ids)]) song = Song.objects.filter(song_id__in=ids).order_by(preserved) return render(request, "music/favourite.html", {'song': song}) This function is … -
Bypassing django-rest-framework APIExceptions
I would like to understand the implications of the following design choice for an application built using DRF. Is it okay if I choose to raise exceptions that are not an instance of APIException in conjunction with a custom_exception_handler that can handle all these exceptions? From what I understand, the handler for a specific request is determined within the rest_framework.views.APIView.dispatch method (source) and the handler gets called within the try...catch.. block in this dispatch method (source). So this way any exceptions that are raised during the execution of the handler are caught within the dispatch method are delegated to the exception handler (default or custom). As we can see here the dispatch method catches not an APIException but any and all Exception. So could I simply raise my own CustomException(s) that are sub-classes of Exception through out my application and simply handle all these exceptions the way I want in the custom_exception_handler? I understand that the ValidationError will be an exception to this, as the serializers and in-built validators all raise ValidationError. If I can override the rest_framework.serializers.Serializer.is_valid in MyCustomSerializer I can catch the rest_Framework.serializers.ValidationError and throw MyOwnCustomValidationError which can be handled by the custom_exception_handler. Something like this: def is_valid(self, … -
How to add many filed in Django
i decided to create movies website with Django , i want to add , for example ** season 1 - series 1 , season 1 - series 2, season 2 - series 1 season 2 - series 1 ** what is best way ? i mean when i add TV shows once and how to add then series and seasons ? this is my model.py class Movie(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) image = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES,max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES,max_length=30) status = models.CharField(choices=STATUS_CHOICES,max_length=100) year_of_production = models.TextField(max_length=10) view_count = models.IntegerField(default=0) link = models.TextField(max_length=70) def get_absolute_url(self): return reverse('post',kwargs={"post_slug":self.slug}) def __str__(self): return "{} -------------- {}".format(self.title,self.status) -
Python/Django Query to check if Dates Overlap
I'm trying to set up a validation on an API built with Python/Django. I'm using a serializer and would like to do a query filter against the post data to make sure 2 date fields do not overlap. For example: My Post contains: "valid_start": "2021-09-01", "valid_end": "2021-09-15" I would like to an object.filter to check if there are any records in my database with overlapping dates: I want to throw a validation error if the query detects any of the following "valid_start": "2021-09-01", "valid_end": "2021-09-15" "valid_start": "2021-09-02", "valid_end": "2021-09-15" "valid_start": "2021-09-03", "valid_end": "2021-09-10" "valid_start": "2021-08-28", "valid_end": "2021-09-20" I've tried the __range function, gte/lte functions, none really do what I'm trying to achieve. Thanks! -
how create simple many-to-many relations with django rest
i am new in django and migrate from symfony. i want to try create simple relation between 2 model in django-rest-framework and get apiview for them. but i can undrestand why serializers not handle relations between this 2 models. my models in models.py from django.contrib.gis.db import models from django.contrib.gis.geos import Point import uuid class RequestLocation(models.Model): gpslocation = models.PointField(srid=4326, geography=True, default=Point(0.0, 0.0)) gpslocationradius = models.IntegerField(default=5) description = models.TextField(default='#') created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created'] def __str__(self): return self.id class Shops(models.Model): gpslocation = models.PointField(srid=4326, geography=True, default=Point(0.0, 0.0)) created = models.DateTimeField(auto_now_add=True) requestlocations = models.ManyToManyField(RequestLocation, null=True, blank=True) class Meta: ordering = ['created'] def __str__(self): return self.id and my serializers in serializers.py: from rest_framework_gis.serializers import GeoFeatureModelSerializer from .models import RequestLocation, Shops class RequestLocationSerializer(GeoFeatureModelSerializer): class Meta: model = RequestLocation geo_field = 'gpslocation' auto_bbox = True id_field = 'id' fields = ['id', 'gpslocation', 'gpslocationradius', 'description'] class ShopsSerializer(GeoFeatureModelSerializer): requestlocations = RequestLocationSerializer(read_only=True) class Meta: model = Shops geo_field = 'gpslocation' auto_bbox = True id_field = 'id' fields = ['id', 'gpslocation', 'requestlocations'] and views.py: # RequestLocation view @api_view(['GET', 'POST']) def rl_list(request, format=None): if request.method == 'GET': rl = RequestLocation.objects.all() serializer = RequestLocationSerializer(rl, many=True) distance_filter_field = 'geometry' filter_backends = (DistanceToPointFilter) bbox_filter_include_overlapping = True return Response(serializer.data) elif request.method == 'POST': … -
Django: The view didn't return an HttpResponse object. It returned None instead. When Override Form_Valid
I overrode the form_valid method on my RobotDetail view but whenever I try to use the view I get the error The view dashboard.views.RobotDetail didn't return an HttpResponse object. It returned None instead. If anybody knows how to fix this it would be super appreciated! VIEW from django.shortcuts import render from django.views.generic import ListView, DetailView, UpdateView from .models import Robot from .forms import RobotUpdateForm import socket import threading HEADER = 64 PORT = 6060 SERVER = socket.gethostbyname(socket.gethostname()) ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT!" class RobotDetail(UpdateView): model = Robot form_class = RobotUpdateForm template_name = 'dashboard/robotdetail.html' def form_valid(self, form): self.object = form.save() client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ADDR) def send(msg): message = msg.encode(FORMAT) msg_length = len(message) send_length = str(msg_length).encode(FORMAT) send_length += b' ' * (HEADER - len(send_length)) client.send(send_length) client.send(message) send("Hello World!") send("Hello Andrew") send("Hello") send(DISCONNECT_MESSAGE) MODEL class Robot(models.Model): def fetch_choices(): scope = [REDACTED] creds = ServiceAccountCredentials.from_json_keyfile_name("dashboard/Files/creds.json", scope) client = gspread.authorize(creds) sheet = client.open("tutorial").sheet1 path_names = [] path_name_fetch = sheet.col_values(1) for i in path_name_fetch: if (i, i) not in path_names: path_names.append((i, i)) return path_names name = models.CharField(max_length=200) path_options = models.CharField(choices=fetch_choices(), default=fetch_choices(), max_length=100) status_choices = [('waiting', 'waiting'), ('running', 'running'), ('stuck', 'stuck')] current_status = models.CharField(choices=status_choices, default=status_choices[0], max_length=100) def __str__(self): return self.name + …