Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Querying related data from a Django model with 2 or more degrees of separation
Suppose I have the following Django models: class Client(models.Model): name = models.CharField(max_length=250) class Staff(models.Model): name = models.CharField(max_length=250) class Agent(models.Model): staff = models.ForeignKey(Staff, on_delete=models.CASCADE) class Writer(models.Model): staff = models.ForeignKey(Staff, on_delete=models.CASCADE) class Order(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) agent = models.ForeignKey(Agent, on_delete=models.CASCADE) writer = models.ForeignKey(Writer, on_delete=models.CASCADE) The relationship between the models have the following conditions: Each order may only have one client Each order may only have one agent Each order may only have one writer A client may have multiple orders An agent may have multiple orders A writer may have written multiple orders Given these models and parameters, how can I get a list of all agents or all writers who have worked with a specific client in the past? I somehow need to query from [Client] > [All Orders] > [Agent per Order] using Python/Django. -
Getting Started with Python but want to implement Web services with Sql backend
I have a mini project that I need to create website site where I can submit some information to a database but want to do it through Web services. Is there any projects that I can reference or tutorial that shows me how to create a Web front end , python web service or django web services tied MS Sql backend. I can do it in another language but really want to do it purely in python/Django or whatever framework that make sense to do it in so I can learn. I'm very committed to learning python but kinda overwhelmed which way to go especially a noob at it. Please help! thanks in advanced!! -
How to make a numpy array field in django?
I want a numpy array field in django so that I can do something like this from example.models import Series import numpy as np array = np.array([1, 2, 3]) model = Series.objects.create(id=1, array=array) model = Series.objects.get(id=1) assert np.array_equal(array, model.array) Essentially, the field should serialize the numpy array to binary and deserialize it automatically. Currently, I'm just doing this: import base64 import numpy as np from django.db import models class Series(models.Model): id = models.IntegerField(primary_key=True, unique=True) array = models.BinaryField() def get_array(): return np.frombuffer(base64.decodebytes(self.array), dtype=np.float32) def set_array(array): self.array = base64.b64encode(array) I'd prefer it if this were a reusable field because I have many models that will need to store a numpy array. For example: class Series(models.Model): array = NumpyArrayField(dtype=np.float32) So, how can I write a NumpyArrayField class that accomplishes this? I tried doing the following (copying the source code for BinaryField) import base64 import numpy as np from django.db import models class NumpyArrayField(models.Field): empty_values = [None] def __init__(self, dtype, *args, **kwargs): self.dtype = dtype super(NumpyArrayField, self).__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super(NumpyArrayField, self).deconstruct() kwargs['dtype'] = self.dtype return name, path, args, kwargs def get_internal_type(self): return 'NumpyArrayField' def get_placeholder(self, value, compiler, connection): return connection.ops.binary_placeholder_sql(value) def get_default(self): if self.has_default() and not callable(self.default): return … -
Integration of css to Django templates
I have a django project and I have added and began integrating bootstrap into my project for the base template as well as other templates that contain the content. I want to know how I can integrate custom css from within my project to finer tune my project and how I want certain things to fit together. I will add the html base template as well as the directory that contans the files to give a reference. Here is the html files: {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "static/css/main.css" %}" rel="stylesheet"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script> </head> <body> <div id="content" class="container-fluid"> {% block content %} {% endblock %} </div> </body> </html> Here is the directory that I have for this project so you can get an idea of where the files are. -
How to use string field values as URL parameters in Django and verify their existence or serve 404?
I have def manufacturer(request, manufacturer_title): #try: # m = Manufacturer.objects.filter(title__iexact=manufacturer_title) #except Manufacturer.DoesNotExist: # raise Http404("No such manufacturer") return HttpResponse("Manufacturer: %s" % manufacturer_title) #return HttpResponse("Manufacturer: %s" % m.title) You can see what I'm trying to do here. With only that second to last line not commented out, this works for any value entered for manufacturer_title, and prints it however it's typed. However clearly I need it to match an existing manufacturer. If I un-comment the above commented lines (excluding the last) the server is unable to connect. -
Django app should to same IP but different port
Have a Django running on https port (443). When user access https://hostname/newAPP, I want Django to redirect to https://hostname:port. I tried the following line in urlpatterns in the urls.py, but could not get the result. url(r'^newAPP$', RedirectView.as_view(url=':8000', permanent=True), name='NewApp') Actually it is getting redirected, but to a wrongly formed url "https:hostname/:8000". Note the ":" is placed after the "/". The server has multiple IPs/hostnames so hard coding the IP/hostname is not an option. -
Where is the Django community?
I am seeking to learn Python & Django, coming from ProcessWire (PHP content management framework) preference. ProcessWire has an amazing community. I'm testing the waters, not very far yet, but alarmingly discouraged by the seeming lack of an active Django community online presence... Is there any secret place hiding somewhere in the folds of the internet where there are active and avid discussions about Django? On Python-Forum.io I checked out the Web Development section and there are next to no replies to threads. -
Set vary: user-agent in nginx
We want to add "user-agent" to vary response header for mobile-seo. I came across some blogs where they say we can do this in nginx like: more_set_headers -s 200 "Vary: " "Accept-Encoding, User-Agent"; ref: https://varvy.com/mobile/vary-user-agent.html We have nginx and django webapp backend. I was wondering if we do this, will it also add the new header to our "www.host.com/api/~" responses too ? What is the way to add it for all routes except: /api/ /webapi/ I dont want to add via django decorators in my different views as I am not sure which view should I add it to. Looking for a simple work around. -
Passing Dictionary from Views to Template
First off, I have looked at many other sources to try and get help, but I feel like I basically have what they have and it just is not working for me. So I have this as my Views: class MVS(ListView): model = VTSI template_name = "templates/mvs.html" def index(request): q = VTSI._meta.get_fields() d = {} for x in q: z = x.verbose_name d.update({z:z}) return render(request, 'mvs', {'d': d}) Simplified, the above class is trying to get all the column names in the models file and get the verbose name of them. It will then take those verbose names, put it in a dictionary, and then pass it to templates to display all those column names. I previously tried passing a list, but I learned that a dictionary is needed to pass values to a template. This is what I have for my templates: {% extends "base.html" %} {% load crispy_forms_tags %} {% load staticfiles %} {% block content %} <div class="row"> <div class="col-sm-3"> <h2>Description of Table</h2> </div> </div> <table id="listview" class='table table-striped table-bordered'> <thead> <tr> <th>Column One</th> <th>Column Two</th> </tr> </thead> <tbody> {% for v in d.items %} <tr> <td> {{ v }}</td> <td> </td> </tr> {% endfor %} </tbody> … -
Ignore uppercase in a query, Python
I have this code query = request.GET.get("q") if query: if query == "song" or query == "songs": return render(request, 'music/cloud.html', { 'songs': song_results, 'generic_songs': song_results_generic, }) The thing is, I want the "if" statement to ignor uppercases. For example, when the user search by "SoNg" or "SonG" or.. it will be converted to "song" before testing -
Adding instances into a different model
I am trying to make a notification app for my Django project. I have this as one of my views: class LikePostToggle(RedirectView): def get_redirect_url(self,pk): obj = get_object_or_404(UserPost,pk=pk) user = self.request.user if user.is_authenticated(): if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) #Add notification to UserNotification model #Auto fill all fields return obj.get_absolute_url() And this is my UserNotification model: class UserNotification(models.Model): user = models.ForeignKey(User,related_name='user',null=True) post = models.ForeignKey('feed.UserPost',related_name='post-notification') timestamp = models.DateTimeField(auto_now_add=True) notify_type = models.CharField(max_length=6) read = models.BooleanField(default=False) def __str__(self): return self.user In the model I think I want the user field to be the user committing the action (Liking, commenting, etc.). My question is how might I go above making it so that whenever someone likes a post or comments and therefore triggers the LikePostToggle view it also adds an instance to the UserNotification model so that the user can be notified? -
Django url paths what is optimal number to cover all combinations
Example: Car Website. If you have a URL structure that goes like this /maker/model/year. Where maker, model, year are the generic default placeholder for any. And replace any part will filter the results. So: /maker/ will list give you a list of car makers like VW or Ford. /Ford/model/ will list all models made by Ford /maker/model_of_car/ will list all models with that name (if two makers have the same name of the model it will list both. /maker/model/ will list all models etc... if you need more example please say. But I hope this is enough to get the idea across. What is the optimal number of URLs need to cover all possibility? Can you show if not all, a critical number of example to get the idea across. So in the form url(r'(?P<maker>[w-]+)/(?P<model>[w-]+/)' (optimal meaning: NOT making just making one super URL that will require a complex view and template to make it work.) I am sorry about the question name, can someone change it to fit the body (if required). I feel like it does not do the body justice. Thank you for your time. -
django ajax, can't capture a list from get ajax request
I'm trying to capture a list of filters in an ajax request, but although I can capture a single filter, when I try to capture a list, I just get an empty list for some reason. Below is the relevant part of my view and the ajax (jQuery) function. When I try and send a single filter with $.ajax({ .... 'filters': fixed }) this works but fails with a list. def quotes_results_filter_view(request): results_filters = request.GET.getlist('filters') or [] quotes_results = request.session['quotes_results'] for results_filter in results_filters: ....... Ajax function: $(document).ready(function () { $('#id_filter').change(function (e) { var fixed = $(this).val() console.log(fixed) $.ajax({ url: '/users/filters/', data: { 'filters': [fixed] }, dataType: 'json', success: function (data) { console.log(data) } }) -
How do you fix this: IntegrityError at /restaurants/create? - NOT NULL constraint failed: restaurants_restaurantlocation.name
Hi I am currently going through a course on UDEMY and have looked for help on that platform and on the web but have no answer. I even looked on here but have struggled to make sense of the answers. The course is to make a django developed website which is called MuyPicky. It is a website which allows you to find restaurants and other things based on your pickiness. I am currently making a page for forms which adds Restaurants to the database. As I am doing this I get this error: IntegrityError at /restaurants/create. It goes on to further say NOT NULL constraint failed: restaurants_restaurantlocation.name Is this why I get the error : The video is called Saving Data The Hard + Wrong Way Here is the forms.py : class RestaurantCreateForm(forms.Form): title = forms.CharField() location = forms.CharField(required = False) category = forms.CharField(required = False) The form.html : {% extends "base.html" %} {% block title %}Add Restaurant || {{block.super}} {% endblock %} {% block content %} <div class="container-fluid"> <div class="container"> <div class="row"> <div class="col-md-offset-4 col-md-4 col-md-offset-4"> <h1>Add Restaurant</h1> <form method="POST">{% csrf_token %} <input title="Title" class="form-control" type="text" name="Title" placeholder="Title"> <br> <input title="Location" class="form-control" type="text" name="Location" placeholder="Location"><br> <input title="Category" class="form-control" type="text" … -
Does Python support the ternary operator ()?: [duplicate]
This question already has an answer here: Does Python have a ternary conditional operator? 19 answers I don't remember what this short if else statement is called in programming in general; ()?: Since I don't remember what it is called I can't actually search for it online. So some examples will help. I have a script where I have to set default values just in case the user has not provided any request parameters. Here is the code; page = request.query_params.get('page'); search = request.query_params.get('search'); search_field = request.query_params.get('search_field'); search_index = request.query_params.get('search_index'); I want to archieve something this; page = (request.query_params.get('page')!=="")?request.query_params.get('page'):1; search = (request.query_params.get('search')!="")?request.query_params.get('search'):"software"; search_field = (request.query_params.get('search_field')!=="")?request.query_params.get('search_field'):'Title'; This produces an error. -
Foreignkey and none value
I have error while try to add in ForeignKey field None value. My model: class Invoice(models.Model): tender_game_id = models.ForeignKey(TenderGame, related_name='invoice_tender_game_id', verbose_name='Tender', blank=True, null=True) makemigration/migrate/syncdb - i did all. I'm receiving everytime error: ERROR:logger:int() argument must be a string or a number, not 'NoneType' What am I doing wrong? Django 1.7 -
django.db.utils.ProgrammingError: relation "bot_trade" does not exist
I am attempting to set up a website on cookeicutter, I created a new app called "bots" and added a class called Trade within models that lists 2 parameters, "titles" and "units". After migrating and running the server, when I open the admin panel and click on the "+ add" button within the panel to create a trade (see picture). The Django Webpage returns this error: django.db.utils.ProgrammingError: relation "bot_trade" does not exist LINE 1: ...."id", "bots_unit"."sell", "bots_unit"."buy" FROM "bots_unit... Additonal Info: Running my django within a docker with postgreSQL pic of admin panel Models.py from django.db import models from datetime import date #from django.contrib.auth.models import AbstractUser #from .models import User from django.urls import reverse from django.urls import reverse_lazy from django.conf import settings import uuid class Unit(models.Model): TRADE_UNIT = ( ('ETH', 'Ethereum'), ('BTC', 'Bitcoin'), ('LTC', 'Litecoin'), ('IOT', 'IOTA'), ('OMG', 'OmiseGo'), ('BCH', 'BitcoinCash'), ) sell = models.CharField(max_length=3, choices=TRADE_UNIT, blank=True, default='ETH', help_text='Currency to Sell') buy = models.CharField(max_length=3, choices=TRADE_UNIT, blank=True, default='BTC', help_text='Currency to Buy') def get_absolute_url(self): """ Returns the url to access a particular author instance. """ return reverse('unit-detail', args=[str(self.id)]) def __str__(self): """ String for representing the Model object. """ return '%s, %s' % (self.sell, self.buy) class Meta: db_table = 'bots_trade' class Meta: ordering … -
Return Default Value When Empty String
In Django, I am pulling values from the request object, and want to set a default if it's empty. I thought I could do something like this: request.POST.get('extended_address', 'this is a default value') But, it's returning an empty string which makes me believe that this only works for None return type. Is there a way to set a default value for a empty string? -
Gunicorn + Gevent : Debugging workers stuck state/ WORKER TIMEOUT cause
I'm running a very simple web server using Django on Gunicorn with Gevent workers which communicate with MySQL for simple crud type operations. All of this is behind nginx and hosted on AWS. I'm running my app server using the following config: gunicorn --logger-class=simple --timeout 30 -b :3000 -w 5 -k gevent my_app.wsgi:application However, sometimes, the workers just get stuck (sometimes when # of requests increase. Sometimes even without it)and the TPS drops with nginx returning 499 HTTP error code. Sometimes, workers have started getting killed (WORKER TIMEOUT) and the requests are dropped. I'm unable to find a way to debug where the workers are getting stuck. I've checked the slow logs of MySQL, and that is not the problem here. In Java, I can take jstack to see the threads state or some other mechanisms like takipi which provides with the then state of threads when an exception comes. To all the people out there who can help, I call upon you to help me find a way to see the internal state of a hosted python web server i.e. workers state at a given point threads state at a given point which all requests a particular gevent worker … -
'NoneType' object has no attribute 'split' : Django 1.9.4
I am working on a project in django with pycharm. I have this view in the views.py : def all_songs(request, filter_by): if not request.user.is_authenticated(): return render(request, 'music/login.html') else: try: song_ids = [] for album in Album.objects.all(): for song in album.song_set.all(): song_ids.append(song.pk) users_songs = Song.objects.filter(pk__in=song_ids) for album in GenericAlbum.objects.all(): for song in album.genericsong_set.all(): song_ids.append(song.pk) generic_songs = GenericSong.objects.filter(pk__in=song_ids) except Album.DoesNotExist: users_songs = [] except GenericAlbum.DoesNotExist: generic_songs = [] return render(request, 'music/songs.html', { 'song_list_all': users_songs, 'generic_song_list': generic_songs, 'filter_by': filter_by, }) Everything is working fine when I click on the page that run this method, but I get an error : Traceback (most recent call last): File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\socketserver.py", line 639, in process_request_thread self.finish_request(request, client_address) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\socketserver.py", line 361, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 99, in init super(WSGIRequestHandler, self).init(*args, **kwargs) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\socketserver.py", line 696, in init self.handle() File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle handler.run(self.server.get_app()) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 144, in run self.close() File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\simple_server.py", line 35, in close self.status.split(' ',1)[0], self.bytes_sent AttributeError: 'NoneType' object has no attribute 'split' but when I change this line for album in Album.objects.all(): with for album in Album.objects.filter(user=request_user), the error disapears. I don't want to use the filter because I want all the albums. I am runing django … -
Django search fields in multiple models
I want to search multiple fields in many models. I don't want to use other apps like 'Haystack' only pure Django. For example: # models.py class Person(models.Model): first_name = models.CharField("First name", max_length=255) last_name = models.CharField("Last name", max_length=255) # other fields class Restaurant(models.Model)/l restaurant_name = models.CharField("Restaurant name", max_length=255) # other fields class Pizza(models.Model): pizza_name = models.CharField("Pizza name", max_length=255) # other fields When I type a 'Tonny' I should get a: "Tonny Montana" from Person model or "Tonny's Restaurant" from Restaurant model or "Tonny's Special Pizza" from pizza model. -
Navbar bootstrap dropdown not working on certain url's
I using a navbar from bootstrap from Carousel Templates And the drop down in my navbar is working but when i go to a specific url in my website is not dropping down and is stuck on highlighted mode for some reason which i cant figure out why i open the console in web seeing if there is any error popping and nothing shown, But when i noticed is that in the url's that it work's when i click on the dropdown it's adding a show class to the but when i click on the problematic url i'm in it isn't adding that class which make me frustrated see more exmple1 exmple2 exmple3 -
Using StreamingHttpResponse with Django Rest Framework CSV
I have a standard DRF web application that outputs CSV data for one of the routes. Rendering the entire CSV representation takes a while to do. The data set is quite large so I wanted to have a streaming HTTP response so the client doesn't time out. However using the example provided in https://github.com/mjumbewu/django-rest-framework-csv/blob/2ff49cff4b81827f3f450fd7d56827c9671c5140/rest_framework_csv/renderers.py#L197 doesn't quite accomplish this. The data is still one large payload instead of being chunked and the client ends up waiting for a response before the bytes are received. The structure is similar to what follows: models.py class Report(models.Model): count = models.PostiveIntegerField(blank=True) ... renderers.py class ReportCSVRenderer(CSVStreamingRenderer): header = ['count'] serializers.py class ReportSerializer(serializers.ModelSerializer): count = fields.IntegerField() class Meta: model = Report views.py class ReportCSVView(generics.Viewset, mixins.ListModelMixin): def get_queryset(self): return Report.objects.all() def list(self, request, *args, **kwargs): queryset = self.get_queryset(self) data = ReportSerializer(queryset, many=True) renderer = ReportCSVRenderer() response = StreamingHttpResponse(renderer.render(data), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="f.csv"' return response NOTE: had to comment out or change some things. Thank you -
Django rest framework use serializer_class in viewset @detail_route
I'm using viewsets with a lot of @detail_route and @list_route. In normal viewsets i use serializer_class and then some validation in serializer but in @detail_route I'm creating serializer in view and check validation here - I know its bad. My question is how to use @detail_route to use like normal modelviewset without need creating serializer manually but use serializer_class in decorator. Its possible to do pagnitation without any addional code in @detail_route? Its better to refactor code and move @detail_route and @list_route to seperated viewsets or stay on viewsets methods? @rest_framework.decorators.detail_route(methods=['post'], serializer_class=orders_serializers.ChangeOrderStatusSerializer) def change_status(self, request, pk=None): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): new_status = serializer.validated_data.get('status') order = self.get_object() if new_status in [orders_models.Order.EXECUTE, orders_models.Order.OUTSIDE]: order.status = new_status order.save() return Response({ 'status': order.get_status_display() }, status=status.HTTP_200_OK) else: return Response('This new status is invalid for this order.', status=status.HTTP_404_NOT_FOUND) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Error: Using the URLconf defined in mysite.urls, Django tried these URL patterns
I'm doing tutorial "Blog" from "Django by example" and i got error. http://127.0.0.1:8000/admin/ works fine. What i'm doing wrong? Error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/post/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^admin/ The current URL, post/, didn't match any of these. mysite/blog/urls.py from django.conf.urls import url from . import views urlpatterns = { # post views url(r'^$', views.post_list, name='post_list'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\ r'(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), } mysite/blog/views.py from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__mounth=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) mysite/blog/admin.py from django.contrib import admin from .models import Post class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'author', 'publish', 'status') list_filter = ('status', 'created', 'publish', 'author') search_fields = ('title', 'body') prepopulated_fields = {'slug': ('title',)} raw_id_fields = ('author',) date_hierarchy = 'publish' ordering = ['status', 'publish'] admin.site.register(Post, PostAdmin) mysite/mysite/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), ]