Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Return HTTP response in the function called by view
In view, I accepts json keys and values in request.body. I plan to check for the existence of the json keys required (typo maybe) in another function def checkJsonKey(form, *args): for key in enumerate(args): if key not in form: return HttpResponse(status = 400) #<-- Instead of doing checking on the returned value, can this function directly return response and terminate this view function? In my view function, form = json.loads(request.body) checkJsonKey(form,"user_preference","model_id", "filename") -
use Django filter but not working?
I made a template to put some posts on it, each post has two category, I use <a> to be the options, like: <div class="cate"> <span class="cate_span0">Species:</span> <a href="?kind={{ post_kind }}"> <span class="cate_span {% ifequal animal_kind '' %}chosen_animal{% endifequal %}">All</span> </a> <a href="?animal=dog&kind={{ post_kind }}"> <span class="cate_span {% ifequal animal_kind 'dog' %}chosen_animal{% endifequal %}">Dog</span> </a> <a href="?animal=cat&kind={{ post_kind }}"> <span class="cate_span {% ifequal animal_kind 'cat' %}chosen_animal{% endifequal %}">Cat</span> </a> <a href="?animal=other&kind={{ post_kind }}"> <span class="cate_span {% ifequal animal_kind 'other' %}chosen_animal{% endifequal %}">other</span> </a> <br/> <span class="cate_span0">Article:</span> <a href="?animal={{ animal_kind }}"> <span class="cate_span {% ifequal post_kind '' %}chosen_animal{% endifequal %}">All</span> </a> <a href="?kind=new_explorer&animal={{ animal_kind }}"> <span class="cate_span {% ifequal post_kind 'new_explorer' %}chosen_animal{% endifequal %}">Stray</span> </a> <a href="?kind=tell_story&animal={{ animal_kind }}"> <span class="cate_span {% ifequal post_kind 'tell_story' %}chosen_animal{% endifequal %}">Story</span> </a> <a href="?kind=giving&animal={{ animal_kind }}"> <span class="cate_span {% ifequal post_kind 'giving' %}chosen_animal{% endifequal %}">Post</span> </a> <a href="?kind=want&animal={{ animal_kind }}"> <span class="cate_span {% ifequal post_kind 'want' %}chosen_animal{% endifequal %}">Want</span> </a> </div> And in my views I use kind and animal filter the DB: animal_kind = request.GET.get('animal', '') post_kind = request.GET.get('kind', '') if animal_kind: all_posts = all_posts.filter(animal_cate=animal_kind) if post_kind: all_posts = all_posts.filter(post_cate=post_kind) And: return render(request, 'community.html', { "all_posts" : posts, "animal_kind" : animal_kind, "post_kind" : … -
Get annual count within the given range of years
I want to track the number of animals born within the given range of years annually. So i may be able to determine which year has the most animals born. I am using this data for graphic reports. class Animal(models.Model): # omitted fields.. date_of_birth = models.DateField() Now the given years would be 2015 to 2017. I would like to get the summary of animal born within that years. E.g. [ {'year': 2015, total: 10}, {'year': 2016, total: 15} {'year': 2017, total: 4} ] So far here is what i did: Animal.objects.filter( date_of_birth__year__range = ( '2017', '2018' ) ).extra( select={'year': 'YEAR(date_of_birth)'} ).values('year').annotate(total=Count('id')).values('year', 'total') But got this: [ { "total": 1, "year": 2015 }, { "total": 1, "year": 2015 }, { "total": 1, "year": 2015 }, { "total": 1, "year": 2015 }, ... and so on to 2017 ] It didn't add the total and it didn't grouped by year. -
Chatterbot Django Integration Retrieving Conversation Data
I am working on a chatterbot django integration. What I need is to retrieve the conversation data entered through django admin console. I define the chatterbot as follows chatbot = ChatBot( "SQLMemoryTerminal", storage_adapter='chatterbot.storage.SQLStorageAdapter', ) Now I am trying to retreive response as follows response = chatbot.get_response("usa money") The response I expect via. admin is "Dollar". But instead of that, I get previously entered statement only. Can anybody help me to retrieve conversation data from the admin console? Thanks. -
Redirect a user to home page if its login?
I am using Django 1.10 and using feature kwargs={'redirect_authenticated_user': True} in my login URL but when I logged in on one tab and hit login page on another tab it still redirects me to login page not on a dashboard page.I may be doing some stupid mistake and not able to track it. my URL: url(r'^$', user.login_user, name='login' ,kwargs={'redirect_authenticated_user': True}), my view:- def login_user(request,**kwargs): title = "Login" form = UserLoginForm(request.POST or None) next = "" if request.GET: next = request.GET['next'] if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") request.session['username'] = form.cleaned_data['username'] user = authenticate(username=username, password=password) login(request, user) if user.is_superuser: if next == "": return redirect('cms:dashboard') else: return redirect(next) elif user.is_staff: if next == "": return redirect('cms:dashboard') else: return redirect(next) else: if next == "": return redirect('cms:dashboard') else: return redirect(next) return render(request, 'templates/login.html', {"form": form, "title": title, "next": next}) -
Loading a new web page overlapped by older webpage in django
I have a webpage which has a login form in one of its frames(say 'f2'). When I submit my form it evalutes and rendering a new webpage in that particular frame(f2). But I need to clear the older webpage and wanna produce my new page over that. Please help!!! -
Django app that checks the disk space
Currently, I'm working on a Django app that will check the disk space (server space in the future) and provide the user about how much space is occupied and how much is left. What is the logic behind creating this app? In the future, I will use this logic to check the server space and display the information to the user. -
Add accounts, retrieve emails (and leave on server) with Python or Django
I want to build an application allowing users to connect their email and social accounts, to be able to receive and reply to all their messages in one place I currently use Django-mailbox library which allow connecting to email accounts (POP3, IMAP, etc) and retrieving email. https://github.com/coddingtonbear/django-mailbox It retrieves emails from the account inbox (for example Gmail/inbox) but deletes them from the server. It can optionally save a copy to another folder (for example Gmail/Archive). http://django-mailbox.readthedocs.io/en/latest/ It cannot leave the messages in the inbox, and specifying the inbox as archive destination causes issues, that cannot or will not be addressed by the repo maintainer. Is there any library out there that allow to easily add email accounts to retrieve emails and leave them on the server inbox? -
Django upload file error? connection error?
I upload a file to Django,but i do not access request.FILES in request views. The browser would not get a response! the tcp connection aborted. so why? "chrome://net-internals/" info: enter image description here uwsgi info: enter image description here -
Vue.js instance data missing when referencing vuex store
I'm attempting to use an api call to a django-rest backend to populate my data-store. The api-call appears to be working fine. After loading index.html i can look at both store_.state.products and v.$store.state.products which both appear to have my json response from the API. You can see that here in the console after navigating to index.html: and However, v.$data as you can see appears to be empty. Please find below my code. products.js //api get call Vue.use(VueResource) function get(url, request) { return Vue.http.get(url, request) .then((response) => Promise.resolve(response)) .catch((error) => Promise.reject(error)) } //data store const apiRoot = 'http://127.0.0.1:8000/api/product-list/?format=json' const store_ = new Vuex.Store({ state: { products: [] }, mutations: { 'GET_PRODS': function (state, response) { state.products = response.body; }, 'API_FAIL': function (state, error) { console.error(error) }, }, actions: { getProducts (store) { return get(apiRoot) .then((response) => store.commit('GET_PRODS', response)) .catch((error) => store.commit('API_FAIL', error)) } } }) //products component Vue.component('product', { template: "#product-template", props: ['product'], delimiters: ["[[","]]"], }) //root instance const v = new Vue({ el: '#app', store: store_, data : function () { return { //this works fine as expected with hardcoded objects fed as data //products : [ //{ // id:1, // name:'test', // brief:'descrip', //}, //{ // id:2, // name:'other', … -
How to use redirect_authenticated_user with extra_context in Django
I am currently using Django v1.11. What I want to happen is, If the authenticated user access the login page they will be redirect. In my case right now they can access the login page even they are authenticated. my previous url.py that extra_context works is this: url(r'^login/$', auth_views.login, {'extra_context': { 'all_user': User.objects.all() }}, name='login') Then base from this documentation: https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.views.LoginView I changed urls.py of login into LoginView.as_view() but the extra_context is not working anymore on my registration/login.html default template. {% for user in all_user %} <option>{{ user.username }}</option> {% endfor %} urls.py url(r'^login/$', auth_views.LoginView.as_view(redirect_authenticated_user=True), {'extra_context': { 'all_user': User.objects.all() }}, name='login') Am I missing something? -
How do I use the same model serializer for my Viewset's 'create' and 'update' methods
When a new client is created, I need them to send back 'confirm_domain_url' so that I can do a check on whether or not it equals 'domain_url'. I call serializer.is_valid() in the create method and it works as intended. When a client is updated, it fails saying that 'confirm_domain_url' is missing. Is there a 'django' way that I can skip calling 'is_valid' so that it doesn't need this field? I know I can just create a new serializer for the update method but I would like to consolidate as much code as I can. Serializer: class ClientSerializer(ModelSerializer): confirm_domain_url = CharField(write_only=True) class Meta: model = Client fields = [ 'name', 'schema_name', 'domain_url', 'created_on', 'id', # Write only fields (won't be returned in the response): 'confirm_domain_url', ] def validate(self, data): # Check that domain urls match: if data['domain_url'] != data['confirm_domain_url']: raise ValidationError('Domain urls do not match.') return data def create(self, validated_data): client = Client( name = validated_data['name'], schema_name = validated_data['schema_name'], domain_url = validated_data['domain_url'], ) client.save() return client ViewSet: class ClientViewSet(viewsets.ViewSet): def list(self, request): queryset = Client.objects.all() serializer = ClientSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Client.objects.all() client = get_object_or_404(queryset, pk=pk) serializer = ClientSerializer(client) return Response(serializer.data) def create(self, request): serializer … -
Django not saving session between redirects to other views
I am using django session data in order to verify that oauth_2 authentication has succeeded. However, django is not saving session data between views. @never_cache def login(request): microsoft = OAuth2Session(client_id,scope=scope,redirect_uri=redirect_uri) global state authorization_url, state = microsoft.authorization_url(authorization_base_url) # State is used to prevent CSRF, keep this for later. request.session['oauth_state'] = state return HttpResponseRedirect(authorization_url) @never_cache def authorization(request): print(request.session.get('oauth_state')) ##This is where I'm having a problem. 'oauth_state' prints none! microsoft = OAuth2Session(client_id,scope=scope,redirect_uri=redirect_uri) token = "" try: users = 'https://graph.microsoft.com/v1.0/me' ##msgraph query url- ##This query is purelyjust used to ##authenticate user! token = microsoft.fetch_token(token_url, client_secret=client_secret,code=request.GET.get('code', '')) header = {'Authorization': 'Bearer ' + token['access_token']} response = requests.get(url = users, headers = header) print(response.text) print(response.status_code) if int(response.status_code) != 200: ##if status code is not 200, then authentication failed. Redirect to login. print ('Not validated. Return to login.') return redirect('http://localhost:8000/login') check_for_authorized = True print(token) except Exception as e: print ('User not does not have authentication rights') return redirect('http://localhost:8000/login') return HttpResponseRedirect('http://localhost:8000/search') Look at the comment beside my print state under the first line of authorization. Why do you think this is? Shouldn't session data be shared between views. -
How to create/signup different User types
I am trying to create two Users; Customers and Restaurants. I used the OneToOneField to relate these to the Django User model. I am confused on how I should go about creating the specific type of user. When I create the user how do I differentiate between which is a Customer and which is a Restaurant? This is what I have thus far, it seems to work but dont feel it is very elegant.. models.py class Restaurant(models.Model): restaurant_user = models.OneToOneField(User, on_delete=models.CASCADE) restaurant_name = models.TextField(max_length=50) about = models.CharField(max_length=500) class Customer(models.Model): customer_user = models.OneToOneField(User, on_delete=models.CASCADE) about = models.CharField(max_length=500) views.py def signup_customer(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] password = request.POST['password'] email = request.POST['email'] #TO DO CHECK IF IT ALREADY EXISTS user1 = User.objects.create_user(username=username, password=password, email=email) user1.save() user = Customer(customer_user=user1) login(request, user1) return redirect('dashboard') -
Fillling an html table with data from two models
I'm trying to enter django model data into a table in my tamplate, which isn't hard by itself. However, trying to find an algorithm that will match model data with rows and columns is difficult for me. I think I could do it using python, but not very efficiently. Trying to use django is even more difficult. Below is a simplified version of my model. Class Headings(models.Model): rowHeading = models.CharField(max_length=60) colHeading = models.CharField(max_length=60) def __str__(self): return self.rowHeading + ':' + self.colHeading Class Information(models.Model): headings = ForeignKey(Headings) info = models.CharField(max_length=100) Views would include something like this class InformationListView(ListView): model = Information def get_context_data(self, **kwargs): context = super(InformationListView, self).get_context_data(**kwargs) context['infos'] = Information.objects.all() context['rowhead'] = Information.objects.values('headings__rowHeading') context['colhead'] = Information.objects.values('headings__colHeading') context['heads'] = Headings.objects.all() return context In the table there could be like 10 rows and 10 columns, but maybe only 4 info. In other words, most of the table cells will be empty. What I've tried so far is to iterate through Headings to build the table but the logic for the cells is difficult. <table> <tr> <th>Big Information</th> {% for col in heads %} <th class="rotate"><div><span>{{ col.colHeading }}</span></div></th> {% endfor %} </tr> {% for row in heads %} <tr> <td>{{ row.rowHeading }}</td> ... … -
Saving image file field manually in django
I am trying to save a preview image generated by "preview_generator" Python app. But I am getting IntegrityError duplicate key value violates unique constraint "users_material_pkey". I've tried many things but nothing seems to be working. If I call super at the end of save I don't get material_file url or path. -
Is Heroku trying to use pip 1.1? And is this the issue?
I'm trying to update a Django app on Heroku from Cedar-10 stack to Heroku-16. I followed the process Heroku outline to update to Cedar-14 (just replacing cedar-14 with heroku-16). I then made a simple change to check it had worked (the instructions say you need to do a git put heroku master for the changes to take place). I got this: Counting objects: 14, done. Delta compression using up to 8 threads. Compressing objects: 100% (13/13), done. Writing objects: 100% (14/14), 116.93 MiB | 866.00 KiB/s, done. Total 14 (delta 8), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ERROR:root:code for hash md5 was not found. remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python2.7/hashlib.py", line 139, in <module> remote: globals()[__func_name] = __get_hash(__func_name) remote: File "/app/.heroku/python/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor remote: raise ValueError('unsupported hash type %s' % name) remote: ValueError: unsupported hash type md5 remote: ERROR:root:code for hash sha1 was not found. remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python2.7/hashlib.py", line 139, in <module> remote: globals()[__func_name] = __get_hash(__func_name) remote: File "/app/.heroku/python/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor remote: raise ValueError('unsupported hash type %s' % name) remote: ValueError: unsupported hash type … -
invalid literal for int() with base ten in listAPI view django rest framework
I am using a view in django rest framework. In this view it takes an argument city to then fetch a list a neighborhoods in that city. the example of the url looks like this: http://127.0.0.1:8000/api/neighborhood-list/chicago/ the url code looks like this: url(r'neighborhood-list/(?P<city>[a-zA-Z]+)/', VenueFilterOptionsView.as_view()), the view: class NeighborhoodListView(generics.ListAPIView): lookup_field = 'city' def list(self, request, city): self.city = city queryset = Neighborhood.objects.filter(city=self.city) serializer = NeighborhoodSerializer(queryset, many=True) the serializer: class NeighborhoodSerializer(serializers.ModelSerializer): class Meta: model = Neighborhood fields = 'neighborhood' the model: class Neighborhood(models.Model): city = models.ForeignKey(City, null=True) neighborhood = models.CharField(max_length=150, null=False) what I don't understand is I set the lookup field to city, unless that only works for instances not lists? And even so I am using the listAPIView generic anyone have any ideas? -
Django Signals stops listening after about 2 calls
So I have the following signal set up post_save.connect(self.increment_on, sender=self.model_dict[self.model_involved], dispatch_uid='increment_for' + self.model_involved + '_creation') The signal works for the first 1-3 saves of the model and then stops running the function ( increment_on ) Is this normal? I am combing through the docs on signals and cant find it. post_save is wrapped in a function, should I call that function again? if so where? -
Invalidate several django cached values efficiently
In my project I have the following model: class Item(models.Model): month = models.DateField('month', null=False, blank=False, db_index=True) kg = models.BigIntegerField('kg') tags = models.ManyToManyField('Tag', related_name='items') // bunch of other fields used to filter data And I have a report_view that returns the sum of kg by month and by tag according to the filters supplied in the URL query. Something like this: -------------------------------- |Tag |jan |fev |mar | -------------------------------- |Tag 1 |1000 |1500 |2000 | -------------------------------- |Tag 2 |1235 |4652 |0 | -------------------------------- As my Item table has already more than 4 million records and is always growing my report_view is cached. So far I got all of this covered. The problem is: the site user can change the tags from the Items and every time this occurs I have to invalidate the cache, but I would like to do it in a more granular way. For example if a user changes a tag in a Item from january that should invalidate all the totals for that month (I prefer to cache by month because sometimes changing one tag has a cascading effect on others). However I don't know all the views that have been cached as there are thousands of possibilities … -
Does the Django localtime template filter work on a local host?
I'm trying to display timezone-aware (I checked) times stored in Django DateTimeFields as the time in the user's timezone. When I use {{ start_time|localtime }} in my templates, the times displayed don't change at all, though, and they're not my local times. We seem to have everything else you need to support timezone awareness. I'm running this locally on a Linux machine (timezone UTC-05:00), and right now the times are output four hours ahead of my actual time. This also happens for our remote host. The admin page indicates that the server time, which is set to UTC, is four hours ahead of my timezone. I am wondering if running this on localhost is part of the problem, but I don't want to push useless code onto our development server if I can avoid it. -
What is the easiest way to start a Django project within an anaconda environment?
I've been using anaconda to create a lot of code, but now I need to put my anaconda code all into a website. So, I have installed the anaconda Django package and manually put the 4 python files into a mysite file inside one of my already created anaconda virtual environments. So, my project directory looks like this: -Django_Stuff __-mysite _____-manage.py _____-mysite ________-___init____.py ________-settings.py ________-urls.py ________-wsgi.py ________-__pycache____ After creating these folders, I ran 'python3 manage.py runserver' in the Mac terminal at the folder mysite(first). And that command gave me the following error: ModuleNotFoundError: No module named '{{ project_name }}' So, I guess I'm just wondering how to fix this problem or how to use another web framework to bypass this problem and get to writing the actual code part faster. Thanks and hope you guys can figure out a solution :) -
Django: Filter paginated list with another URL parameter
I have list of games that I am displaying with Paginator. I would like to also be able to filter games by their genre. In my view I have simple code to check, if genre parameter ("zanr") is part of the URL: genre = request.GET.get('zanr') if genre: free_games_list = free_games_list.filter(category__id=genre) On my view page, I have HTML Select with genre names and their ID as values. I have not so pretty JS code that redirects to new page after item in Select is selected: $('#select').change(function () { var selectElement = $(this); var url = window.location.href; if (url.indexOf('?') > -1) { url += '&zanr=' + selectElement.val(); } else { url += '?zanr=' + selectElement.val(); } window.location.href = url; }); This works fine with the first genre select. But when I select another genre, the parameter in URL is now simply duplicated like so: zanr=5&zanr=4&zanr=3 I thought about doing more JS to remove the parameter but I guess there will be far better and simpler option how to do this. I also tried doing it as a Select inside of Form but had problems passing the selected value.. -
Django - distinct() does not work with annotate()
I have these models (very simplified) class Offer(models.Model): product = ForeignKey(Product) class Conversation(models.Model): user = ForeignKey(settings.AUTH_USER_MODEL) receiver = ForeignKey(settings.AUTH_USER_MODEL) offer = ForeignKey(Offer, related_name='conversations') last_message = OneToOneField('Message', null=True, blank=True) class Message(models.Model): message = TextField() status = CharField( max_length=128, choices=constants.MESSAGE_STATUS_CHOICES, default=constants.MESSAGE_STATUS_SENT, ) sender = ForeignKey(settings.AUTH_USER_MODEL) conversation = ForeignKey(Conversation) created_at = DateTimeField(auto_now_add=True) I want to bring offers with conversations, ordered by messages not seen first, so I thought I'd use annotations to indicate if the offer is seen or not, but distinct() does not work with annotate(): class User(AbstractUser): def get_offers_with_conversations(self): """ Get offers with conversations. Not seen conversations first.' """ return Offer.objects.filter( Q(conversations__user=self) | Q(conversations__receiver=self), ).annotate(seen_conversations=Case( When( ~Q(conversations__last_message__sender=self) & Q(conversations__last_message__status=conversation_constants.MESSAGE_STATUS_SENT), then=Value(True) ), default=Value(False), output_field=BooleanField() )).order_by( '-seen_conversations', '-conversations__last_message__created_at' ).distinct() Any help will be welcome. Thank you. -
django templates not found
I have already looked for almost all question but still any of the answers isn't working for me . Screen Shot My BASE_DIRS = "/home/amank/Adevelopment/test/mechanical/templates" This is okay but still django is looking in different irrelevant paths as shown in screen shot ... my related settings import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) . . . TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'debug': DEBUG, 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] (Any method to give templates path manually in settings.py)