Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting error while fetching value from file using Python and Django
I need some help. I am trying to display the value in a tabular format but getting the following error using Django and Python. The error is given below. raise SyntaxError("invalid predicate") SyntaxError: invalid predicate def search(request): per=[] if request.method == 'POST': rname=request.POST.get('rname') serch=request.POST.get('searchby') tree = ET.parse('roomlist.xml') root = tree.getroot() if serch==0: xyz = './/*[roomname=' xyz = xyz + rname xyz= xyz + ']' result=root.findall(xyz) for x in result: per.append({'roomname':x.find('roomname').text,'seat':x.find('noseats').text,'project':x.find('projectorscreen').text,'video':x.find('videoconf').text}) return render(request,'booking/home.html',{'people': per}) My view part is given below. home.html: {% if people %} <table> <tr> <th>Room Name</th> <th>seats</th> <th>Projector screen</th> <th>Video Conference</th> </tr> {% for person in people %} <tr> <td>{{person.roomname}}</td> <td>{{person.seat}}</td> <td>{{person.project}}</td> <td>{{person.video}}</td> </tr> {% endfor %} </table> {% else %} <p>No Record in the database</p> {% endif %} I need to fetch all value from the below .xml file. <?xml version="1.0" ?><roomlist> <location name="Bangalore"> <room id="1uy92j908u092"> <roomname> Aquarius </roomname> <noseats> 10 </noseats> <projectorscreen>yes</projectorscreen> <videoconf>yes</videoconf> </room> </location> <location name="Bhubaneswar"><room id="131198912460"><roomname>cottage</roomname><noseats>5</noseats><projectorscreen>Yes</projectorscreen><videoconf>Yes</videoconf></room></location><location name="puri"><room id="509955554930"><roomname>room1</roomname><noseats>10</noseats><projectorscreen>No</projectorscreen><videoconf>Yes</videoconf></room></location></roomlist> Here I need to search all value from file and display. Please help me. -
'Types' object has no attribute 'decode' AttributeError at /print/8
Im try to print the item in python-django by "ReportLab PDF" and i have an error like this: AttributeError at /print/8 'Types' object has no attribute 'decode' I have codes in 9 files models.py class Games(models.Model): title = models.CharField(max_length=50) type = models.ForeignKey("Types") date_of_production = models.DateField() producer = models.ForeignKey("Producers") availability = models.BooleanField() account = models.IntegerField() language = models.ForeignKey("Languages", default='') price = models.CharField(max_length=10) abbr = models.CharField(max_length=5) def __str__(self): return self.title class Producers(models.Model): name = models.CharField(max_length=10) date = models.DateField() def __str__(self): return self.name class Types(models.Model): type = models.CharField(max_length=10) def __str__(self): return self.type class Languages(models.Model): language = models.CharField(max_length=15) def __str__(self): return self.language Admin.py from django.contrib import admin #from main.models import Game from main.models import Games from main.models import Producers from main.models import Types from main.models import Languages # Register your models here. #admin.site.register(Game) admin.site.register(Games) admin.site.register(Producers) admin.site.register(Types) admin.site.register(Languages) forms.py from django import forms class GamesForm(forms.Form): title = forms.CharField(label= "Nazwa gry", max_length=50) type = forms.CharField(label= "Typ gry", max_length=10) date_of_production = forms.DateField(label= "Data produkcji") producer = forms.CharField(label= "Nazwa producenta", max_length= 10) availability = forms.BooleanField(label= "Czy jest dostępne?") account = forms.IntegerField(label= "Ilość dostępnych sztuk") language = forms.CharField(label= "Języki", max_length=50) price = forms.CharField(label= "Cena", max_length=10) abbr = forms.CharField(label= "Skrót waluty", max_length=5) class ProducersForm(forms.Form): name = forms.CharField(label= "Nazwa producenta", max_length=10) … -
Django redirectView returns None
I'm trying to use redirect view in django, but I keep getting this error: The view gp_accountant.gp_taxes.views.TaxRateDeleteView didn't return an HttpResponse object. It returned None instead. I've based my code on this question. Anyone knows where the problem lies? This is my url file (path: get-paid/gp_accountant/gp_taxes/urls.py): app_name = 'gp_taxes' urlpatterns = [ url(r'^$', TaxesListView.as_view(), name='list'), url( r'^delete_rate/(?P<pk>\d+)/$', TaxRateDeleteView.as_view(pattern_name='accountant:gp_taxes:update'), name='delete_rate' ), ] The TaxRateDeleteView: class TaxRateDeleteView(RedirectView): def dispatch(self, request, *args, **kwargs): TaxRate.objects.get(id=int(kwargs['pk'])).delete() -
Django multiple products with different fields, into one cart
Scope: Create a website with different kinds of products Renew a vehicle license: This includes: 1.1. Arrears based on 3 rates: the current rate Last years rate The year before last rate 1.2 Penalties based on 3 rates: As above but percentage is less 1.3. The current price for renewal for this year Buy numberplates: These have set prices and sizes( a very "normal" product) Pay for infringements(fines): These have only the following: 3.1. The infringement number 3.2. The infringement amount Buy backing plates: As with numberplates Renew drivers license: 5.1. Amount With my absolutely limited knowledge of Python and Django, I first did the following: I created 5 different apps. Each of them have their own product as a model. Each product has its own fields as needed for that specific product. It worked liked a charm. I could show lists of: Vehicle licenses the client wishes to renew Drivers licenses the client wishes to renew Fines he wishes to pay Products he wants to purchase(number-plates and backing-plates) But, then I created the shopping cart. I thought this would be easy. From vehicles.models import Product From drivers.models import Product From plates.models import Product etc. BUT: It will NOT work … -
User has no dcf_profile : RelatedObjectDoesNotExist
After extending an existing user model, I get RelatedObjectDoesNotExist exception with a value User has no dcf_profile. I seems that dcf_profile isn't created automatically for each user. Please take a look at my model, view and form below and tell me how can I correct my views file? My models.py : class CustomUser(models.Model): auth_user_ptr = models.OneToOneField( User, parent_link=True, related_name='dcf_profile', primary_key=True ) phone = models.CharField(_('phone'), max_length=30, null=True, blank=True) receive_news = models.BooleanField(_('receive news'), default=True, db_index=True) class Meta: app_label = 'dcf' def allow_add_item(self): if self.item_set.count() > settings.DCF_ITEM_PER_USER_LIMIT: return False else: return True class Item(models.Model): slug = models.SlugField(blank=True, null=True, max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group, verbose_name=_('group')) title = models.CharField(_('title'), max_length=100) description = models.TextField(_('description')) price = models.DecimalField(_('price'), max_digits=10, decimal_places=2) phone = models.CharField(_('phone'), max_length=30) is_active = models.BooleanField(_('display'), default=True, db_index=True) updated = models.DateTimeField(_('updated'), auto_now=True, db_index=True) posted = models.DateTimeField(_('posted'), auto_now_add=True) def __unicode__(self): return self.title class Meta: verbose_name = _('item') verbose_name_plural = _('items') ordering = ('-updated', ) def get_absolute_url(self): return reverse('item', kwargs={ 'pk': self.pk, 'slug': self.slug }) def get_title(self): return u'%s' % self.title def get_description(self): return u'%s' % self.description[:155] def get_keywords(self): # TODO need more optimal keywords selection return ",".join(set(self.description.split())) def get_related(self): # TODO Need more complicated related select return Item.objects.exclude(pk=self.pk)[:settings.DCF_RELATED_LIMIT] def save(self, *args, **kwargs): if self.slug … -
Django - is it possible to show full inline form?
I have inline form setup for many-to-many field class DaysInline(admin.TabularInline): model = Reservation.reserved_days.through class ReservationAdmin(admin.ModelAdmin): inlines = (DaysInline,) exclude = ('reserved_days',) it looks like this if i click on edit, form appears in new window Is it possible to show full form on each line instead of select ? So i can see edit form for each entry directly on page, without clicks -
arrange keys order in a django queryset
I have this Django query where I get some information from different databases, which I want to expose to the front end: specifics = PageData.objects.filter(page_id__in=page_ids).values('page_id'). \ annotate(views=Count('page_id')). \ values('views', 'page__title', 'page__content_size') that gives me in turn a list of dictionaries - the prompt is for list(specifics): [ {'page__content_size': 19438L, 'page__title': u'Bosch Tassimo Charmy anmeldelse. Positivt: Bryggehastighed. Negativt: Placering af vandtanken. | 96 Grader', 'views': 5}, […] {'page__content_size': 19395L, 'page__title': u'Banwood First Go Balance Bike - studiominishop.com', 'views': 1} ] I would like to be able to arrange the order of the keys in each dictionary. The order would always be the same for each element in the list. I read a lot about how to sort a dictionary by keys and/or values, but I have not found much about how to sort the keys. Here one says that 'the dictionary implementation doesn't guarantee any specific order.' Is there any way to do it in Django or in Python? -
Django : UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 1: ordinal not in range(128)
I created a new Django app Deces with models.py, forms.py etc .. and I want to make a Django migration in order to creater table in my Database. I got an ascii error and I don't understand pretty well the Traceback, especially where the error is located : Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/valentinjungbluth/Desktop/Django/DatasystemsEC/Etat_civil/Deces/models.py", line 26, in <module> class Acte_Deces(models.Model): File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 310, in __new__ new_class._meta.apps.register_model(new_class._meta.app_label, new_class) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 216, in register_model self.do_pending_operations(model) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 412, in do_pending_operations function(model) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 391, in apply_next_model self.lazy_model_operation(next_function, *more_models) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 403, in lazy_model_operation apply_next_model(model_class) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 391, in apply_next_model self.lazy_model_operation(next_function, *more_models) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 377, in lazy_model_operation function() File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 313, in resolve_related_class field.do_related_class(related, model) File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 374, in do_related_class self.contribute_to_related_class(other, self.remote_field) File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 915, in contribute_to_related_class super(ForeignKey, self).contribute_to_related_class(cls, related) File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 707, in contribute_to_related_class setattr(cls._meta.concrete_model, related.get_accessor_name(), self.related_accessor_class(related)) UnicodeEncodeError: 'ascii' … -
PostgreSQL with Python
I have a running and working database in SQLite but multiple users are writing to it in the same time and i seem to have concurrency problems, because of the database being locked. What do i need in order to create and access a PostgreSQL database in Python? Is there a way in which i dont install anything else than python libraries? I have a company laptop and would need 1XXXX approvals to install a third party software. The setup is simple: The users go to the upload page on the site(built in django), uploads a xls file and the info gets extracted into a database(while being compared with info from inside the database). If 2 users try to upload files in the same time, i get database locked error. Any help would be great, either to solve this SQLite problem or to get me started in Postgre if this should solve it. THX! -
Python UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 12: ordinal not in range(128)
I am trying to return a file in a StreamingHttpResponse from a class based view using Django rest framework. However I get a very cryptic error message with a stack trace that does not contain any references to my code: 16/Jun/2017 11:08:48] "GET /api/v1/models/49 HTTP/1.1" 200 0 Traceback (most recent call last): File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 138, in run self.finish_response() File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 179, in finish_response for data in self.result: File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/util.py", line 30, in __next__ data = self.filelike.read(self.blksize) File "/Users/jonathan/anaconda/lib/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 12: ordinal not in range(128) [...] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 141, in run self.handle_error() File "/Users/jonathan/anaconda/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 88, in handle_error super(ServerHandler, self).handle_error() File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 368, in handle_error self.finish_response() File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 180, in finish_response self.write(data) File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 274, in write self.send_headers() File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 331, in send_headers if not self.origin_server or self.client_is_modern(): File "/Users/jonathan/anaconda/lib/python3.6/wsgiref/handlers.py", line 344, in client_is_modern return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9' TypeError: 'NoneType' object is not subscriptable My get method looks like this: def get(self, request, pk, format=None): """ Get model by primary key (pk) """ try: model … -
Django low performance with Mysql on seperate Instance
I have configured my application on Goolge Cloud Platform. I am using CloudSQL for database connection. Here my database params in settings. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '133.193.218.243' 'NAME': 'test', 'USER': 'test', 'PASSWORD': 'test', } } http://staging.audiotube.com/test/ this url doesn't have any database interaction it just show the static html. But It takes 3 to 4 seconds for First Byte. Obviously the above mentioned database is on seperate instance. I have changed the Database to DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase', } } So this will be installed in local this time http://staging.audiotube.com/test/ would take only 400milliseconds to load. Questions? Why this much of delay for the First Byte and How to reduce this? On every request DB connection will open? even if there is static pages? -
Django - edit many-to-many inline
I have following model class Day(models.Model): date = models.DateField(auto_now=False, auto_now_add=False) price = models.FloatField() payment_method = models.CharField(max_length = 200, blank=True) payment_date = models.CharField(max_length=200, blank=True) room = models.ForeignKey(Room, null=True, blank=True, verbose_name='Номер', on_delete=models.CASCADE) def __unicode__(self): return str(self.date) class Reservation(models.Model): start = models.DateField(verbose_name='Заезд', auto_now=False, auto_now_add=False, blank=False) end = models.DateField(verbose_name='Выезд', auto_now=False, auto_now_add=False, blank=False) check_in_time = models.TimeField(verbose_name='Время заезда', blank=False) check_out_time = models.TimeField(verbose_name='Время выезда', blank=False) has_refund = models.BooleanField(verbose_name='Возвратная бронь', default=True) payed = models.BooleanField(verbose_name='Оплачено', default=False) reserved_days = models.ManyToManyField(Day, blank=False) additional_services = models.ManyToManyField(AdditionalService) guest_name = models.CharField(verbose_name='Имя гостя', max_length=200, blank=True) reservation_number = models.CharField(verbose_name='Номер брони', max_length=200, blank=True) What I want is to have ability to edit Day on Reservation page I try the following as in the django docs class ReservedDaysInline(admin.TabularInline): model = Reservation extra = 1 class ReservationAdmin(admin.ModelAdmin): inlines = (ReservedDaysInline,) class DayAdmin(admin.ModelAdmin): inline = (ReservedDaysInline,) admin.site.register(Reservation, ReservationAdmin) admin.site.register(Day, DayAdmin) But it doesnt work. What am I doing wrong ? -
Django with Postgresql, column must appear in the GROUP BY clause or be used in an aggregate function
I'm using Django 1.11 and Postgresql 9.6 In my app, there is a model called Person, it have several fields. In database, it's a materialized view. class Person(models.Model): personid = models.CharField(max_length=18, primary_key=True) count = models.BigIntegerField() native = models.CharField(max_length=2) ... When execute persons = Person.objects.values('personid', 'native')\ .annotate(total=Count('native')) It says psycopg2.ProgrammingError: column "person.native" must appear in the GROUP BY clause or be used in an aggregate function When only select one column or not set the personid as primary key or not execute annotate it won't get error. I print the query sql: SELECT "person"."native", "person"."personid", COUNT("person"."native") AS "total" FROM "person" GROUP BY "person"."native", "person"."personid" Is there any problem? -
Django urls. Click on the button and redirect to the same page
Hej, I have a problem with urls. Through the button I'm passing to the url appropriate id, in controller I'm taking this id and assign it to the current date to save it in database (table with users then admin clicks on "attend" and save lastAttendance in database). I'm stacked with urls cause after clicking it doesn't redirect me to the same page. Any advices appreciated! MODEL: class Donor(models.Model): firstName = models.CharField(max_length=50) lastName = models.CharField(max_length=50) bloodType = models.CharField(max_length=10) createdDate = models.DateTimeField(auto_now_add=True) lastAttendance = models.DateTimeField(auto_now_add=True) URLS: url(r'^donors/get?attend=(\d+)/$', views.donors, name='donors'), VIEW: @login_required(login_url="login/") def donors(request): global message if request.method == 'POST': form = PostForm(request.POST) # A form bound to the POST data if form.is_valid(): form.save() # context = RequestContext(request) donor_id = None if request.method == "GET": donor_id = request.GET.get('id') if donor_id: donor = Donor.objects.get(id=int(donor_id)) if donor: donor.lastAttendance = datetime.datetime.now() donor.save() #display all the lates added donors query_results = Donor.objects.order_by('-createdDate') #dislay total ammount of rows donors_count = Donor.objects.count() return render(request, 'donors.html', { 'form': PostForm(), 'donors_count': donors_count, 'query_results': query_results, }) HTML: <button type="submit" class="btn attendBtn" value="{{ item.id }}" name="attend">attend OUTPUT output in the browser Any help will be appreciated !! -
How to force download an image on click with django and aws s3
I have this view, which takes a user_id and image_id. When the user cliks the link, check if there is an image. If there is, then I would like the file to force download automatically. template: <a class="downloadBtn" :href="website + '/download-image/'+ user_id+'/'+ image_id +'/'">Download</a> Before I was developing it in my local machine, and this code was working. @api_view(['GET']) @permission_classes([AllowAny]) def download_image(request, user_id=None, image_id=None): try: ui = UserImage.objects.get(user=user_id, image=image_id) content_type = mimetypes.guess_type(ui.image.url) wrapper = FileWrapper(open(str(ui.image.file))) response = HttpResponse(wrapper, content_type=content_type) response['Content-Disposition'] = 'attachment; filename="image.jpeg' return response except UserImage.DoesNotExist: ... But now I am using aws s3 for my static and media files. I am using django-storages and boto3. How can I force download the image in the browser? @api_view(['GET']) @permission_classes([AllowAny]) def download_image(request, user_id=None, image_id=None): try: ui = UserImage.objects.get(user=user_id, image=image_id) url = ui.image.url ... ... FORCE DOWNLOAD THE IMAGE ... except UserImage.DoesNotExist: ... ... ERROR, NO IMAGE AVAILABLE ... -
how to fix NoReverseMatch at? work if you not authorized
If you are not authorized, then everything will work fine, as soon as you authorize, for example, adeline, this error will be issued, I do not know what happened! NoReverseMatch at /series/Colony/Season_1/Episode_1/ Reverse for 'post_of_serie' with no arguments not found. 1 pattern(s) tried: ['series/(?P<serial_slug>[\\w-]+)/(?P<season_slug>[\\w-]+)/(?P<series_slug>[\\w-]+)/$'] main urls.py from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^series/', include("serials.urls", namespace='series')), url(r'^', include("serials.urls", namespace='homeview')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) second urls.py to app(series) from django.conf.urls import include, url from .views import homeview, post_of_serial, post_of_season, post_of_serie, validate_email, mark_and_unmark_this_episode urlpatterns = [ url(r'^$', homeview, name='homeview'), url(r'^subscribe/$', validate_email, name='subscribe'), # /series/ url(r'^mark_or_unmark_this_episode/$', mark_and_unmark_this_episode, name="mark_and_unmark_this_episode"), url(r'^(?P<serial_slug>[\w-]+)/$', post_of_serial, name='post_of_serial'), # /series/Prison_Break/ url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/$', post_of_season, name='post_of_season'), # /series/Prison_Break/season_5/ url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/(?P<series_slug>[\w-]+)/$', post_of_serie, name='post_of_serie'), # /series/Prison_Break/season_5/2/ ] error this is part of view.py def post_of_serie(request, serial_slug=None, season_slug=None, series_slug=None): serie = get_object_or_404(Series, serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug) #print(serie) title = serie.serial_of_this_series.rus_name_of_seriall full_path = All_Images_Of_The_Series.objects.filter(to_series__serial_of_this_series__slug=serial_slug, to_series__season_of_this_series__slug=season_slug, to_series__slug=series_slug, is_poster=True) context = {"serie":serie, "full_path":full_path, "title":title,} try: userr = request.user check_button = watched_series.objects.filter(user=request.user, watched_serial__slug=serial_slug, watched_serie__season_of_this_series__slug=season_slug, watched_serie__slug=series_slug ) context["check_button"] = check_button context["userr"] = userr except: pass return render(request, 'series.html', context) if delete somethig in views.py nothing change!!! -
How to dynamically create queryset on the fly?
Using Django 1.10, Python 3.5, I have stored various information about the columns and tables I want to use to extract data in another table called smart_view That smart_view has the following columns: id (auto increment) name (varchar 255) columns (jsonb type) tables (jsonb type) conditions (jsonb type) I want to dynamically create queryset based on the records in smart_view. I read about dynamically generate columns using an answer from https://stackoverflow.com/a/4720109/80353. Is that applicable to my situation and how do I do the same for the tables (or Model) part? -
Django-haystack: How to filter product listings based on price?
I'm currently using elasticsearch2 with django-haystack. I've been able to achieve filtering based on facets for some product listings (cars). The next step is to filter based on a price range. I have a form that allows a min input and a max input. Any thoughts on how I can achieve this? Thank you. -
How to search value from xml file as per user input in different way using python and Django
I need one help.I need to search the data as per user input using Python and Django. I am explaining my code below. <form method="post" action="{% url 'search' %}"> <label>Search by Room name: </label> <input name="rname"> <input type="submit" value="Submit"> </form> {% if people %} <table> <tr> <th>Location Name</th> <th>Room Name</th> <th>seats</th> <th>Projector screen</th> <th>Video Conference</th> </tr> {% for person in people %} <tr> <td>{{person.lname}}</td> <td>{{person.roomname}}</td> <td>{{person.seat}}</td> <td>{{person.project}}</td> <td>{{person.video}}</td> </tr> {% endfor %} </table> {% else %} <p>No Record in the database</p> {% endif %} Here I need to search the value as per room name from .xml file which is given below. roomlist.xml: <?xml version="1.0" ?><roomlist> <location name="Bangalore"> <room id="1uy92j908u092"> <roomname> Aquarius </roomname> <noseats> 10 </noseats> <projectorscreen>yes</projectorscreen> <videoconf>yes</videoconf> </room> </location> <location name="Bhubaneswar"><room id="131198912460"><roomname>cottage</roomname><noseats>5</noseats><projectorscreen>Yes</projectorscreen><videoconf>Yes</videoconf></room></location><location name="puri"><room id="509955554930"><roomname>room1</roomname><noseats>10</noseats><projectorscreen>No</projectorscreen><videoconf>Yes</videoconf></room></location></roomlist> Here I need different type of search. 1- simple search by user input. 2- URL encode paste contents in the request before passing it to the model layer 3- give special characters with the input and search. Please help me to resolve this problem -
Django creates log file but doesn't write into it
I am trying to use Django logger by giving the following settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'simple': { 'format': '[%(asctime)s] %(levelname)s %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, }, 'handlers': { 'logfile': { 'level': 'INFO', 'filters': ['require_debug_false','require_debug_true'], 'class': 'logging.FileHandler', 'filename': '/tmp/django-log.log', 'formatter': 'simple' }, }, 'loggers': { 'user_activity': { 'handlers': ['logfile',] }, } } and then using it in the view like following: user_logger = logging.getLogger('user_activity') ... user_logger.info("opened page") Although Django creates file django-log.log, it doesn't write to it. Is there a problem with my settings? Thanks -
Reversing the result of Django's naturaltime
Django's humanize module is fantastic for turning datetime objects into something that makes more sense to us as humans with it's naturaltime function (docs). What I'm trying to do is the reverse, taking any one of the naturaltime formats and converting it back to a datetime (accepting the obvious loss of precision). Is there any existing library to do this or am I going to have to write my own datetime.strftime patterns? -
how to select all id's of all sequnces in postgresql?
I'm using the Django-Framework. For each model, django generates a relation with a unique id and a squence. e.g.: relations: myapp__mymodel_a myapp__mymodel_b myapp__mymodel_c sequences: myapp__mymodel_a__id_seq myapp__mymodel_b__id_seq myapp__mymodel_c__id_seq Each relation has a unique field "id". Every id-field has a correspondent squence, amongst others with a field "last_value". Now I need a SQL command, to get the last_values of all sequences, ending with "_id_seq". Could someone please help me, including explanations? Thanks! -
How to run javascript on individual form fields in django
I am currently trying to get my registration template to work, and i am trying to make sure that the username entered is unique before the submit the form using javascript and ajax. I am doing so by following this tutorial. My question is, rendering my form using {{ form.as_p }} is there anyway i can do what theyre doing, or will I have to type out every field as they have? -
How to search the value from xml file using Django and Python
I need some help. I need to search the value from xml sheet using Django and Python. I am explaining my code below. <form method="post" action="{% url 'search' %}"> <label>Search by Room name: </label> <input name="rname"> <input type="submit" value="Submit"> </form> {% if people %} <table> <tr> <th>Location Name</th> <th>Room Name</th> <th>seats</th> <th>Projector screen</th> <th>Video Conference</th> </tr> {% for person in people %} <tr> <td>{{person.lname}}</td> <td>{{person.roomname}}</td> <td>{{person.seat}}</td> <td>{{person.project}}</td> <td>{{person.video}}</td> </tr> {% endfor %} </table> {% else %} <p>No Record in the database</p> {% endif %} Here I need to search by room name and it should be done by below process. 1-Application uses SQL Query to search for the room(use sql query to search xml data). The user input (room name) is direct without any validation resulting in injection attack. 2-Use prepared statement and pass arguments to it properly I need to do it in either way. I am explaining my xml file below. <?xml version="1.0" ?><roomlist> <location name="Bangalore"> <room id="1uy92j908u092"> <roomname> Aquarius </roomname> <noseats> 10 </noseats> <projectorscreen>yes</projectorscreen> <videoconf>yes</videoconf> </room> </location> <location name="Bhubaneswar"><room id="131198912460"><roomname>cottage</roomname><noseats>5</noseats><projectorscreen>Yes</projectorscreen><videoconf>Yes</videoconf></room></location><location name="puri"><room id="509955554930"><roomname>room1</roomname><noseats>10</noseats><projectorscreen>No</projectorscreen><videoconf>Yes</videoconf></room></location></roomlist> Please help me to resolve this. -
Running Django from Python IDLE
I know that running django scripts is easy in Pycharm or any other software. But I just want to know whether the django scripts can be done using the python shell? If there is then I want to to how to code the script in idle shell.