Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Best practice to generate access token for api auth in django
I am very new to django and I am building a backend that authenticates user through access token. Currently I am generating token with sha1 with email and some random numbers. I am very new to programming and I am looking for best practice. What will be the best approach to generate access token. Also, I would be glad if someone guide me through refresh token and how to use it. If I generate the token it will only be used but what if I want to refresh token continously according to some time or on every login so that use dont get authenticated with same access token. -
django return the most recent record of each user
I am learning django framework, and currently I am facing a problem. There are two models class User(models.Model): name = models.CharField(max_length=30) ... class Action(models.Model): user = models.Foreign(User) action = models.CharField(max_length=30) createTime = models.DateTimeField(default=django.utils.timezone.now) Each action from each user is inserted into Action Model, therefore, there are lots of records of each user in Action by different createTime. Now, I would like to list the latest action of each user, but I have no idea to implement it. -
How to upload files into BinaryField using FileField widget in Django Admin?
I want to create a model Changelog and make it editable from Admin page. Here is how it is defined in models.py: class Changelog(models.Model): id = models.AutoField(primary_key=True, auto_created=True) title = models.TextField() description = models.TextField() link = models.TextField(null=True, blank=True) picture = models.BinaryField(null=True, blank=True) title and description are required, link and picture are optional. I wanted to keep this model as simple as possible, so I chose BinaryField over FileField. In this case I wouldn't need to worry about separate folder I need to backup, because DB will be self-contained (I don't need to store filename or any other attributes, just image content). I quickly realized, that Django Admin doesn't have a widget for BinaryField, so I tried to use widget for FileField. Here is what I did to accomplish that (admin.py): class ChangelogForm(forms.ModelForm): picture = forms.FileField(required=False) def save(self, commit=True): if self.cleaned_data.get('picture') is not None: data = self.cleaned_data['picture'].file.read() self.instance.picture = data return self.instance def save_m2m(self): # FIXME: this function is required by ModelAdmin, otherwise save process will fail pass class Meta: model = Changelog fields = ['title', 'description', 'link', 'picture'] class ChangelogAdmin(admin.ModelAdmin): form = ChangelogForm admin.site.register(Changelog, ChangelogAdmin) As you can see it is a bit hacky. You also can create you own … -
Django: one authentication backend per user model
in my Django application I need multiple type of Django users: 1. A typical admin user which is identified by email and authenticated with password. 2. A remote application which connects to django and authenticates with pre-shared key and tokens. The email is not required for such type of user. Every type of user has different associated attributes. I know that I can extend User model in Django. I already created email authentication backend. But this works for all the accounts, including the remote applications ones. Is there any effective way to create a auth backend for a type of user? -
Django domain forwarding
I have a Django site which will show different things depending on the subdomain visited. So you will see "A"-type things if you go to a.mysite.com but "B"-type things if you go to b.mysite.com. I do this by gathering the subdomain in the request and using that to filter. What I want to be able to do is allow any other domain to point at these subdomains (like, for instance, heroku can do) but still allow me to do the filtering in the above way. Is that possible? If so, how would I go about it? I assume that, if a user comes to my site on theirdomain.com (which points at a.mysite.com) then I won't have "a" in the subdomain so how do I know they want to see "A"-type things?