Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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')), ] -
Local version of Heroku-Django app does not see vars in .env
I cloned my Heroku-Django project to a new Windows computer. I don't have the local_settings.py file on this computer, so I am trying to set it up to use local environment variables. I used heroku config:get SECRET_KEY -s >> .env to put the config var into my .env file. That appears to have worked. The .env file now reads SECRET_KEY='mysecretkey'. The actual key is correct. Because I am on Windows, I created a separate Procfile called Procfile.windows and it reads: web: python manage.py runserver 0.0.0.0:8000 In my production_settings file, I have this line: SECRET_KEY = os.environ.get('SECRET_KEY'). OS is imported. When I run heroku local -f Procfile.windows, I ultimately get this error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. However, it does find the .env file: [OKAY] Loaded ENV .env File as KEY=VALUE Format. Am I missing something? -
Django ORM : Categorizing a list query on multiple foreign keys
My title may seem vague, but I'm sorry to save I have no other idea on how to phrase this. Assuming my model structure looks like this: class Restaurant(models.Model): name = models.CharField(...necessary stuff...) class Cuisine(models.Model): name = models.CharField(...necessary stuff...) # thai chinese indian etc. class Food(models.Model): restaurant = models.ForeignKey(Restaurant, related_name='restaurant') cuisine = models.ForeignKey(Cuisine, related_name='cuisine') name = models.CharField(...) What I want is a list of objects of Food of a specific restaurant. But the Food objects need to be under their respective Cuisine, so that I can easily access the Food through the context. Is it possible to achieve this in any way? My current query: q = Cuisine.objects.prefetch_related('cuisine') q = q.filter(cuisine__restaurant_id=restaurant.id) # say restaurant.id=1 # here restaurant is the object which I have retrieved Well, what it does is it filters the cuisines available to the restaurant, but lists all food within those cuisine. I want only the food available in the restaurant. I think I am missing something in the way I built my models, but I'm not certain. It would be really helpful if someone could point me to the right direction. Thanks. -
how to style this django form?
{% extends 'base.html' %} {% block head %} {% endblock head %} {% block body %} <div> <div class="container" id="outer"> <div> <h1>User Login Form</h1> </div> <div> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-block">Login</button> </form> </div> </div> </div> {% endblock body %} i had made this code without using forms.py and getting trouble for styling the forms.so please try to solve my problem. thanks.. -
DJANGO Multiple views on same page and one model
I have two elements on my index page, and both of the elements are using the same model. First element is list of all the locations, queried in a way that every location show only once. This element has it's own view: class Home(ListView): model = models.Dadilja template_name = 'accounts/index.html' def get_queryset(self): return Dadilja.objects.values_list('mjesto', flat=True).distinct().order_by("-mjesto") Second element is list of top 5 people from that database, with their first name, last name, profile pic, location and rating. This element is using the same model as the first element, but has it's own view: class DadiljaTopFive(ListView): model = models.Dadilja template_name = 'accounts/top5.html' def get_queryset(self): return Dadilja.objects.all() What is interesting is that both of these queries affect each other somehow. For example, If I leave both views it will show locations right, but list of top 5 people will only show location, in order that is displayed in location list. On the other side, people list is rendered right if I remove view of locations. I even tried to write function base view for locations in order to successfully show both elements: def mjesto(request): return render_to_response('accounts/index.html', { 'mjesta': Dadilja.objects.values_list('mjesto', flat=True).distinct().order_by("-mjesto") }) But... nothing seems to work. Does anybody know why is this … -
How to capture the subdomain in a django view?
I'm developing an aplication in django with many subdomains. For example www.mysite.com, mx.mysite.com, es.mysite.com, nz.mysite.com All of these patterns have to redirect to the same django aplication and render the html page with the country language. is there any way to capture the sub domain in the views.py? I want something like this in views.py: ######## VIEWS.PY ########### def hompage(request): subdomain = #HERE IS WHERE I WANT TO CAPTURE THE SUBDOMAIN if subdomain=='www': contextdict = {"Language": "English"} else if subdomain=='mx': contextdict = {"Language": "Spanish"} return render(request, 'mysite/index.html', contextdict) -
Django: Default Image from ImageField wont show
I'm trying to simply display an Image from an ImageField within a template. class Profile(models.Model): img = models.ImageField(upload_to='profiles/profile_pictures', default="/profiles\profile_pictures\default_profile_picture.PNG") Django returns that the Image is not found: Not Found: /media/profiles/profile_pictures/default_profile_picture I've been looking to solve this for quite a while now and I can't seem to see why it won't show. I'added + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to my urls.py also I've added MEDIA_ROOT and MEDIA_URL to my settings. # media MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' I've checked the paths multiple times now. The files definitely exist in the given path. What have I forgotten?