Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is not redirecting after receiving a POST request
I'm trying to send some values from the front-end to a Django app. I want to manipulate those values and then redirect to another view, but it seems that Django is not redirecting nor rendering nothing. This is my urls.py from django.conf.urls import url from . import settings from personality_form import views urlpatterns = [ url(r'^$', views.home, name="home"), url(r'^apiLogin/(?P<_id>\d+)$', views.apiLogin,name="apiLogin"), url(r'^formulario/(?P<_id>\d+)$', views.formulario, name="formulario"), ] This is my views.py from django.shortcuts import render, redirect from personality_form.models import * from personality_form.forms import * from django.views.decorators.csrf import csrf_exempt def home(request): return render(request, 'index.html') def formulario(request, _id): if (request.method == 'POST'): form = personalityForm(request.POST) else: form = personalityForm() return render(request, 'formulario.html', {'form': form}) @csrf_exempt def apiLogin(request, _id): if (request.method == 'POST'): return redirect('formulario/'+_id) And this is the javascript function that I'm using to send the POST request from the front. function test() { var http = new XMLHttpRequest(); http.open('POST', '/apiLogin/1234', true); http.setRequestHeader('Content-type', 'application/json'); var payload = {userID: "1234", access: "4567"}; var params = JSON.stringify(payload); // Send request http.send(params); } I've tried to send the POST to apiLogin view. I check that it is entering on that view but when I try to redirect to formulario view, it enters on formulario code but don't seems … -
message is not shown
I am making a web site by seeing Django tutorial.But message in results.html is not shown. results.html is {% extends "polls/base.html" %} {% load bootstrap3 %} {% block contents %} <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'polls:polls_detail' question.id %}">Vote again?</a> {% endblock contents %} results.html inherits base.html. base.html is {% load staticfiles %} {% load bootstrap3 %} <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../../favicon.ico"> <title>Starter Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <style type="text/css"> body { padding-top: 50px; } </style> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{% url 'index' %}">Tutorial</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class="{% block nav_polls %}{% endblock %}"><a href="{% url 'polls:index' %}">polls</a></li> <li class=""><a href="{% url 'admin:index' %}">admin</a></li> </ul> </div><!--/.nav-collapse --> </div> </nav> <div class="container"> {% if messages %} {% bootstrap_messages messages %} {% endif %} {% … -
Django - How to get the maximum value after distinct on fields
I have those models: class Product(models.Model): name = CharField(max_length=128) other_fields... class Price(models.Model): product = ForeignKey(Product) store = CharField(max_length=128) price = DecimalField(max_digits=10, decimal_places=2) date = DateField() the products table contains some products (...) and the price table gets update each time a store change the product price. I want to get the latest price ("current price") from every store, and then get the maximum and the average price of each product. I tried it first for one product: Price.objects.filter(product__id=42).order_by('store','-date').distinct('store').annotate(Max('price')) but got: NotImplementedError: annotate() + distinct(fields) is not implemented. I also tried to add order_by('-price') to get the maximum, but it ordered first by date, so it's useless. Any suggestion how to do it without multiple queries and nasty loops? -
Retrofit Android miss some response from server(not all)
when I try to send some request in a for loop, log of the server is ok(all request recieved and all responses sent) but in Android Studio Emulator i have only some those responses not all. here My request code private void updateDatabase(JsonArray arrayJson) { final List<JsonObject> user_cars= new ArrayList<JsonObject>(); for(JsonElement a : arrayJson){ String carID = a.getAsString(); carID=carID.substring(0,carID.length()-1); int index = carID.lastIndexOf('/'); Integer id =Integer.parseInt(carID.substring(index+1)); Log.e("Index",id.toString()); AdaClient client = ServiceGenerator.createService(AdaClient.class); Call<JsonObject> call = client.retrieveCars(id); call.enqueue(new Callback<JsonObject>() { @Override public void onResponse(Call<JsonObject> call, retrofit2.Response<JsonObject> response) { Log.e("user_cars",response.body().toString()); user_cars.add(response.body()); } @Override public void onFailure(Call<JsonObject> call, Throwable t) { } }); } The request are 7 as you can see in my log id = 08-29 12:55:20.497 19654-19654/it.uniroma3.adateam.ada E/Index: 1 08-29 12:55:20.499 19654-19654/it.uniroma3.adateam.ada E/Index: 2 08-29 12:55:20.505 19654-19654/it.uniroma3.adateam.ada E/Index: 3 08-29 12:55:20.506 19654-19654/it.uniroma3.adateam.ada E/Index: 4 08-29 12:55:20.508 19654-19654/it.uniroma3.adateam.ada E/Index: 5 08-29 12:55:20.511 19654-19654/it.uniroma3.adateam.ada E/Index: 8 08-29 12:55:20.512 19654-19654/it.uniroma3.adateam.ada E/Index: 9 Here logcat 08-29 12:55:20.748 19654-19654/it.uniroma3.adateam.ada E/user_cars: {"id":1,"owner":"raul@raul.raul","car":"http://10.10.10.10:8080/cars/60546/","total_km":null,"tires_km":null,"oil_km":null,"breaks_km":null,"engine_km":null,"insurance_date":null,"vehicle_tax_date":null} 08-29 12:55:20.826 19654-19654/it.uniroma3.adateam.ada E/user_cars: {"id":3,"owner":"raul@raul.raul","car":"http://10.10.10.10:8080/cars/60550/","total_km":null,"tires_km":null,"oil_km":null,"breaks_km":null,"engine_km":null,"insurance_date":null,"vehicle_tax_date":null} 08-29 12:55:20.855 19654-19654/it.uniroma3.adateam.ada E/user_cars: {"id":4,"owner":"raul@raul.raul","car":"http://10.10.10.10:8080/cars/60551/","total_km":null,"tires_km":null,"oil_km":null,"breaks_km":null,"engine_km":null,"insurance_date":null,"vehicle_tax_date":null} 08-29 12:55:20.863 19654-19654/it.uniroma3.adateam.ada E/user_cars: {"id":2,"owner":"raul@raul.raul","car":"http://10.10.10.10:8080/cars/60548/","total_km":null,"tires_km":null,"oil_km":null,"breaks_km":null,"engine_km":null,"insurance_date":null,"vehicle_tax_date":null} 08-29 12:55:20.915 19654-19654/it.uniroma3.adateam.ada E/user_cars: {"id":8,"owner":"raul@raul.raul","car":"http://10.10.10.10:8080/cars/60550/","total_km":null,"tires_km":null,"oil_km":null,"breaks_km":null,"engine_km":null,"insurance_date":null,"vehicle_tax_date":null} 08-29 12:55:20.936 19654-19654/it.uniroma3.adateam.ada E/user_cars: {"id":9,"owner":"raul@raul.raul","car":"http://10.10.10.10:8080/cars/60547/","total_km":null,"tires_km":null,"oil_km":null,"breaks_km":null,"engine_km":null,"insurance_date":null,"vehicle_tax_date":null} Here my server response : [29/Aug/2017 12:55:36] "GET /user-cars/1/ HTTP/1.1" 200 [29/Aug/2017 12:55:36] "GET /user-cars/3/ HTTP/1.1" 200 [29/Aug/2017 12:55:36] "GET … -
Django send mail works locally but on server it's not sending mail
I have a normally working smpt mail working on localhost but when i put the app on server its not sending mails. I think there is some configuration problem. I am using apace2 ubuntu server 14.04 and i have placed my project in /var/www/ folder. I am forcing https connection by configuring 000-default.conf file Settings.py TEMPLATE_DEBUG =False SECRET_KEY = **key** DEBUG = False ALLOWED_HOSTS = [**allowed hosts**] import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = ( 'index', 'aboutus', 'aboutus.team', 'aboutus.careers', 'aboutus.locations', 'aboutus.board', 'domainsec', 'projects', 'downloads', 'contactus', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) X_FRAME_OPTIONS = 'DENY' ROOT_URLCONF = **urls** TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'antef.wsgi.application' # Email EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = **emailid** EMAIL_HOST_PASSWORD = **password** EMAIL_PORT = 587 EMAIL_USE_TLS = True apache_config file: <VirtualHost *:443> RewriteEngine On RewriteCond %{HTTP_HOST} ^www\. [NC] RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301] RewriteEngine on SetEnvIfNoCase User-Agent ^libwww-perl bad_bot BrowserMatchNoCase SpammerRobot bad_bot BrowserMatchNoCase SecurityHoleRobot bad_bot <Location /> Order allow,deny Allow from all Deny from env=bad_bot </Location> <IfModule mod_headers.c> Header set … -
Determine if an M2M field has a custom through model
With a custom through model for an M2M relationship, .add(), .create() and .remove() are disabled. At the moment, I attempt to use .add() (or whatever) and catch and deal with AttributeError for those custom M2M relationships. Is there an 'official' way to identify a custom through model, using the Meta API or otherwise? At this stage in my processing I would rather treat all custom through relationships as generically as possible (rather than lots of if m2m_field.related.through == FooBar statements) (Django 1.8, but if there's a solution for a later version we will be upgrading before long.) -
Django - getting list of values after annotating a queryset
I have a Django code like this: max_id_qs = qs1.values('parent__id').\ annotate(max_id = Max('id'),).\ values_list('max_id', flat = True) The problem is that when I use max_id_qs in a filter like this: rs = qs2.filter(id__in = max_id_qs) the query transforms into a MySQL query of the following structure: select ... from ... where ... and id in (select max(id) from ...) whereas the intended result should be select ... from ... where ... and id in [2342, 233, 663, ...] In other words, I get subquery instead of list of integers in the MySQL query which slows down the lookup dramatically. What surprises me is that I thought that Django's values_list returns a list of values. So the question, how should I rewrite the code to achieve the desired MySQL query with integers instead of id in (select ... from...) subquery -
Create instances of subclasses at application start
I need to create an instance for all subclasses of a given class, where __subclass__() is still empty due to application loading. tl; dr Is there a module (built-in or pypi) which finds all subclasses of a specified class before they are instantiated, probably by using static code inspection? Example There is one class that sets up a data structure at the very start of application loading, lets assume: autostart_this.py class Foo: """ Setup data structure, instances must be created at application start and before models.py is loaded. """ def __init__(module_name): print(module_name) def some_method(): raise NotImplementedError() Several modules define a specific data structure, extending from given class: some_module.py class CustomizedFoo(Foo): def some_method(): pass CustomizedFoo('some_module') My hook into the application start shows an empty list of subclasses for Foo, as autostart_this.py is loaded before any other module: Foo.__subclasses__() [] If the application is fully loaded, the subclasses are available - but then it's too late to add the data structure... Assumptions There is a naming convention for files implementing subclasses of Foo. I probably need to find all modules where Foo is imported, and need to do so in a more or less 'static' way (i.e. using https://docs.python.org/3/library/inspect.html or https://docs.python.org/3/library/pyclbr.html). Question … -
Django iterate over check boxes
Trying to dynamically create a list of checkboxes that when selected will perform an action. I have the checkboxes created as expected, and I have an action working as expected. I can't seem to get a hold of the correct box(s) to perform the action on. For example, when I click the third box, or the second and third box the action is always performed on the first box. I have verified that the POST data is correctly passing the checked boxes prefix's and form name's, but somehow I am telling the code that if a box is checked, perform the action on the first instance rather than on the checked box or boxes. Here is what I have: forms.py class remove_resource(forms.Form): active = forms.BooleanField(label_suffix='', label='', required=False) views.py def edit_project_resource (request, offset): list_resources = Allocation.objects.filter(project_id=offset).filter(active=True).order_by('user_id').distinct('user_id') display = {} for r in list_resources: check = remove_resource(prefix = r.pk) display[r.user_id] = (check, r.user_id) if request.method == 'POST': check = remove_resource(request.POST, prefix = r.pk) if check.is_valid(): if request.POST.get(check, True): Allocation.objects.filter(project_id=offset).filter(user_id = r.user_id).update(active=False) return HttpResponseRedirect('/project_profile/%s/' % offset) -
Django uploaded file in admin list
I've read several posts here on this problem and have tried many of the approaches - in the end I returned to the Django docs. I'm trying to get the uploaded image to appear in the admin list... My models.py (based on info from here: Django Docs) from django.db import models from django.contrib import admin from django.utils.html import format_html class File(models.Model): file = models.ImageField() description = models.CharField(max_length=200) def __str__(self): return self.description def image_tag(self): return format_html( '<img src="{}" />', self.file ) class FileAdmin(admin.ModelAdmin): list_display = ('image_tag', 'description') This, sadly, does nothing however... I have tried putting arbitrary HTML as well - just in case file url is bad...but nothing changes. Any ideas would be greatly appreciated - quite frustrated with this now. -
Fake JSONField using Factory Boy
I have a field in my model with JSONField Type(MYSQL Implementation). I want to fake the data for this field using FactoryBoy Faker. How can I achieve this? -
ProgrammingError when trying to add Keycloak authentication to OpenShift Django template
I am trying to add Keycloak authentication to the Django template code basis in OpenShift (https://github.com/openshift/django-ex) I have been following the blog post http://blog.jonharrington.org/static/integrate-django-with-keycloak/ and I am documenting my progress at: https://github.com/OpenRiskNet/home/blob/master/openshift/django_keycloak_example.md The thing is that I ahve made it almost all the way but when I try to view a page from Django that needs authentication I get an eror message about: relation "bossoidc_keycloak" does not exist LINE 1: INSERT INTO "bossoidc_keycloak" ("user_id", "UID") VALUES (1... which indicate that something is wrong in the database. When I look in the logs for stuff related to migrations I see: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, welcome Running migrations: No migrations to apply. Which first made me happy because it clearly states Apply all migrations and then made me worried because it doesn't list the bossoidc to be migrated. Why is it not migrating this stuff? -
Django annotate not working with two apps
I have two applications in my project. Models.py of first app has model: class repair(models.Model): site = models.ForeignKey('second.site') price = models.FloatField() … Models.py of second app has model: class site(models.Model): name = models.CharField(max_length = 250) When I do in shell: repair.objects.values('site__name').annotate(sum_site=Sum('summ')) i am getting all items of repair model with their prices: <QuerySet [{'site__name': 'Site-1', 'count_ss': 1500.0}, {'site__name': 'Site-2', 'count_ss': 1500.0}, {'site__name': 'Site-1', 'count_ss': 800.0}, {'site__name': 'Site-1', 'count_ss': 230.0}, {'site__name': 'Site-2', 'count_ss': 90.0}]> How I can group by site? -
Django Validating email address and username in forms.py
I am trying to check whether the entered in email address and username to form has ever been used. The code works fine for when the email address and username do not exist in the database however I get an invalid form in views.py otherwise. I would like a text validation error message to appear in the form when the user attempts to submit. forms.py class UpdateProfileForm(ModelForm): class Meta: model = UpdatedInformation fields = ('email', 'username',) def clean_email(self): username = self.cleaned_data.get('username') email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).exclude(username=username).count(): raise forms.ValidationError('This email address is already in use. Please supply a different email address.') return email def clean_username(self): username = self.cleaned_data.get('username') email = self.cleaned_data.get('email') if email and User.objects.filter(username=username).exclude(email=email).count(): raise forms.ValidationError( 'This username is already in use. Please supply a different username.') return username views.py @login_required def update_profile(request, slug): args = {} #Check that the correct user has requested if not slug == slugify(request.user.username): raise Http404 #Get the user object from the database by its username user = get_object_or_404(User, username=request.user.username) #Create a new updated information object to initialise the form with update_profile_obj = UpdatedInformation() update_profile_obj.username = user.username update_profile_obj.email = user.email if request.method == 'POST': form = UpdateProfileForm(request.POST) print(form.errors) if form.is_valid(): #Get the updated_info … -
immutable variable for unit tests
I have some test cases which rely on the same variable foo from unittest import TestCase class TestFoo(TestCase): def setUp(self): self.foo = {'key_a': aaa, 'key_b': bbb} def test_a(self): self.foo['key_a'] = 'ccc' self.assertEqual(self.foo['key_a'], 'ccc') def test_b(self): self.assertEqual(self.foo['key_a'], 'aaa') the issue I have is that once I change the value in test_a to self.foo['key_a'] = 'ccc' the value "stays" this way for all subsequent tests. the assert in test_b fails because the value of self.foo['key_a'] remains at 'ccc' how do I have to write the test case so foo is {'key_a': aaa, 'key_b': bbb} in all tests? -
In django models how to update a particular column after creating
I have models.py as below, class members(models.Model): id = models.AutoField(primary_key=True) HID = models.IntegerField(blank=False,unique=True) owner = models.ForeignKey(User) member_name = models.CharField(max_length=25, blank=False, default='') father_name = models.CharField(max_length=25, blank=False, default='') wife_name = models.CharField(max_length=25, blank=False, default='') Now in the above HID value is entered manually each time. When there is a new member is getting inserted I am planing to enter my previous member HID value after which the insertion should be done, so that all entries after that should be updated with HID + 1. I tried to implement this with linked list model like having one more with next_HID= , but here the issue is my insertion is very less like yearly one or 2 but query is more so then each time this list has to be created by doing query. so I thought to update the HID number each time after insert. Please let me know how can I run an update query after every insert in django models for the above purpose -
Validating data in bootstrap modal using JQuery not working
I have been stuck on this issue since a week. I am not able to validate bootstrap modal using jQuery validator function. I have searched lots of stuff, also I have used exactly the same method as mentioned in here: How to correctly validate a modal form . I have been using django framework. Here is my HTML code: <div class="modal fade" id="myModalHorizontal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <form class="form-horizontal" id="myForm" role="form" action="{% url 'apply:add' %}" method="POST"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">&times;</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title" id="myModalLabel"> Apply Leave </h4> </div> <!-- Modal Body --> <div class="modal-body"> <div class="form-group"> <label class="control-label col-sm-3" for="e_id">Employee-Id</label> <div class="col-sm-9"> <select class="form-control" id="e_id" name="e_id" class="required"> {% for entry in emp_data %} <option value="{{ entry.emp_id }}">{{ entry.emp_id }} - {{ entry.emp_name}} </option> {% endfor %} </select> </div> </div> <style> .datepicker { z-index: 1600 !important; border-color: black; } </style> <div class="form-group"> <label class=" control-label col-sm-3" for="s_dt">Start Date</label> <div class="col-sm-9" > <input type='text' class="form-control" id="s_dt" placeholder="Start Date" name="s_dt"/> </div> </div> <div class="form-group"> <label class="control-label col-sm-3" for="e_dt">End Date</label> <div class="col-sm-9" > <input type='text' class="form-control" id="e_dt" placeholder="End Date" name="e_dt" require/> </div> </div> <p class="col-sm-9 col-sm-offset-3" > … -
Building an app for all platforms
What is best? android studio or ionic or something else to build an app in less time and that can be easily built and also it should be available for all users -
how to use multiple settings files in django in live server
I am a beginner in django and i have a website which i have used the sites framework to make it use the same code and database for multiple sites but i can't handle this in the live server, i have a settings file with different SITE_ID for every instance of this site. This is my wsgi.py code which i have to point the DJANGO_SETTINGS_MODULE to the current site settings file but how can i make it dynamic with the current site settings file? import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() What am i missing ? Can any one help me ? thanks. -
Which package should i use with django to implement social login in august 2017?
I started development with Python Django and explored so many packages like python-social-auth, Django-all-auth, and Django-social-auth. After Lots of research, I found that all packages have their pros and cons. Like Django-social-auth was deprecated and merged into python-social-auth and now I found auth that Python-social-auth also has been deprecated. Django All Auth has lots of problems when it comes to creating a custom model. So Now I'm really confused what to choose and need help in this.I want to choose the one for which I will get longer support and good for lot of customizations. -
Django CreateView with form_class not creating model
I'm practicing from Two Scoops of Django book and i have a problem with form_class in CreateView. If i'm using just fields in the CreateView it's saving the model, if i'm using the form_class it's not saving and not redirecting either. I'm using form_class for practicing validators. views.py class FlavorCreateView(LoginRequiredMixin, CreateView): model = Flavor success_url = '/flavors/list/' template_name = 'flavor_create.html' success_msg = 'Flavor created.' form_class = FlavorForm # fields = ['title', 'slug', 'scoops_remaining'] def form_valid(self, form): form.instance.created_by = self.request.user return super(FlavorCreateView, self).form_valid(form) forms.py class FlavorForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(FlavorForm, self).__init__(*args, **kwargs) self.fields['title'].validators.append(validate_tasty) self.fields['slug'].validators.append(validate_tasty) class Meta: model = Flavor fields = ['title', 'slug', 'scoops_remaining'] validators.py def validate_tasty(value): """ Raise a ValidationError if the value doesn't start with the word 'Tasty'. """ if not value.startswith('Tasty'): msg = 'Must start with Tasty' raise ValidationError(msg) flavor_create.html {% extends 'base_flavor.html' %} {% block content %} <form action="" method="POST">{% csrf_token %} <p style="color: red;">{{ form.title.errors.as_text }}</p> {% for field in form %} <p>{{ field.label }}: {{ field }}</p> {% endfor %} <button type="Submit">Salveaza</button> </form> <a href="{% url 'flavors:list_flavor' %}">Return home</a> {% endblock %} -
How to log out using rest framework jwt
How to log out using rest framework jwt. How can I close the existing token for the logged in user? Just as there is a get_jwt_token function, is there a function to break or close? Thank you very much -
recive message from user with telegram bot - Django
I have a bot and a website and i want when a user send me a command (i set command in past) and i just replay to user his message and write some thing to user : For example : user : /message mybot : (replay his message)you send me a command But i dont know how to recive his command(or message). My coding language in django.(if there is a way with php tell me too) note : bot send updaytes to website and website send again message to bot. note : if there is project on github or some result for me in here(stackovwerflow),tell me . -
Django date time filter?
I have a createdAt field in my database which stores the current time stamp.And when I render it to my templates it returns in the form of Aug. 24, 2017, 12:58 p.m.. What I want it to return in the form of Aug. 24, 2017, 12:58 PM.That is am/pm should be in caps form. what I tried in my templates are:- <td>{{ item.newsId.createdAt|time:"g:iA" }}</td> and what it returned is only time 10:27AM.But I want the date also along with this time format. -
Access to fields of on reverse relation in django
I have this models: class Task(models.Model): user = models.ForeignKey(User) name = models.CharField() class Report(models.Model): task = models.ForeignKey( Task, blank=True, null=True, related_name='+') status = models.CharField(max_length=32, choices=Status.CHOICES, default=Status.INCOMPLETE) now I want to get all Task and related status. How do I access all task and related status? Thanks a lot in advance!