Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render date format in Django template?
I am trying to output the date format in a Django template using {{ DATE_FORMAT }} and {{ settings.DATE_FORMAT }}, but all that comes out is an empty string as far as I can see. Let me be clear, I'm not trying to render a date using the format, but the date format string itself. Expected output is something like dd.mm.yyyy in case the LANGUAGE_CODE is set to de. Is there any way to get to it inside a template? PS: There are both USE_I18N = True and USE_L10N = True in settings. -
cannot resolve keyword 'user' into field. choices are
I am trying to edit data of model UserProfile. Here is code for same. form.py class UserprofileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['profile_photo', 'gender', 'contact_number', 'age', 'address'] view.py def edit_user(request): if not request.user.is_authenticated(): return render(request, 'service/login.html') else: userdata = UserProfile.objects.all().filter(user = request.user) userd = UserProfile.objects.get(user2 = request.user.pk) form = UserprofileForm(request.POST or None, instance = user2) if form.is_valid(): user1 = form.save(commit = False) user1.user = request.user user1.save() return render(request,'service/user.html', {'userdata' : userdata,}) -
Tango With Django ModuleNotFoundError: No module named 'registration'
I have cloned this repository as part of a tutorial and gone into the directory tango_with_django_19/code/tango_with_django_project to run the command: $ python maange.py runserver In order to run the web app. However, I received the following errors: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f6e2c1782f0> Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/usr/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'registration' I am using Manjaro Linux and have installed the packages python-django and python-django-extensions with pacman. How can I resolve this error so that I can run the web app? I have not changed after cloning the aforementioned repo. -
How to raise form validation if during form initialisation in djnago
I am making a project which consists of different conferences and different talks related to them. What I wanted to do is to check for a condition that if the conference end date is passed/expired than the current_date/today then the user can not be able to modify the title of the form fields but can edit other fields.So to check it i have added a line in my update_view function in which the parameters are the conference to which the particular proposal belong if not conference.end_date < datetime.now().date(): proposal.title = form.cleaned_data['title'] The above line is effcient to make a constrain but it is done silently,he will try to change the title but will not be able to do without getting any error , i want some method like form validation error method that he/she can not change the title . and to generate the dynamic/custom form i have used def __init__(self, conference, action="edit", *args, **kwargs): This above line is for dynamic form , so i am finding no efficient way to raise a form error.Is there any chance that i can raise form validation error from views.py file except forms.py file.Is not how should i notify(except from form validation) the … -
String concatenation by using the value of the model field while updating a queryset
I want to update the email id of some users to: "prefix" + "value of the user email" Now I can do this for one user as follows: User.objects.filter(pk=<id>).update(email=Concat(Value("prefix"), 'email')) However, as soon as I filter on a pk list, I get a nasty error. The query is: User.objects.filter(pk__in=<list_id>).update(email=Concat(Value("prefix"), 'email')) The error is: /Users/zishanahmad/Devel/Env/venv_sliderule/lib/python2.7/site-packages/django/db/models/query.pyc in update(self, **kwargs) 561 query.add_update_values(kwargs) 562 with transaction.atomic(using=self.db, savepoint=False): --> 563 rows = query.get_compiler(self.db).execute_sql(CURSOR) 564 self._result_cache = None 565 return rows /Users/zishanahmad/Devel/Env/venv_sliderule/lib/python2.7/site-packages/django/db/models/sql/compiler.pyc in execute_sql(self, result_type) 1060 related queries are not available. 1061 """ -> 1062 cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) 1063 try: 1064 rows = cursor.rowcount if cursor else 0 /Users/zishanahmad/Devel/Env/venv_sliderule/lib/python2.7/site-packages/django/db/models/sql/compiler.pyc in execute_sql(self, result_type) 838 cursor = self.connection.cursor() 839 try: --> 840 cursor.execute(sql, params) 841 except Exception: 842 cursor.close() /Users/zishanahmad/Devel/Env/venv_sliderule/lib/python2.7/site-packages/django/db/backends/utils.pyc in execute(self, sql, params) 77 start = time() 78 try: ---> 79 return super(CursorDebugWrapper, self).execute(sql, params) 80 finally: 81 stop = time() /Users/zishanahmad/Devel/Env/venv_sliderule/lib/python2.7/site-packages/django/db/backends/utils.pyc in execute(self, sql, params) 62 return self.cursor.execute(sql) 63 else: ---> 64 return self.cursor.execute(sql, params) 65 66 def executemany(self, sql, param_list): /Users/zishanahmad/Devel/Env/venv_sliderule/lib/python2.7/site-packages/django/db/utils.pyc in __exit__(self, exc_type, exc_value, traceback) 96 if dj_exc_type not in (DataError, IntegrityError): 97 self.wrapper.errors_occurred = True ---> 98 six.reraise(dj_exc_type, dj_exc_value, traceback) 99 100 def __call__(self, func): /Users/zishanahmad/Devel/Env/venv_sliderule/lib/python2.7/site-packages/django/db/backends/utils.pyc in execute(self, sql, params) 62 return … -
django query generate LEFT OUTER JOIN instead of INNER JOIN
I try to do a simple query on my app but the result is wrong because Django ORM generate a LEFT OUTER JOIN . But I'd like the result of an INNER JOIN Here is a part of my model : class Application(models.Model): """ Une application """ app_name = models.CharField(max_length=20) app_pub_date = models.DateTimeField(auto_now_add=True, editable=True) class Event(models.Model): """ Evenement status """ STATUS = ( ('OK', 'OK'), ('KO', 'KO'), ('DEGRADE', 'DEGRADE'), ) app = models.ForeignKey(Application, on_delete=models.CASCADE) status_start = models.DateTimeField() status_end = models.DateTimeField(null=True, blank=True, editable=True) status_global = models.CharField(max_length=20, choices=STATUS,default='OK') I tried to retrieve all the 'application' objects having an "opened event" (which means an event that has a Null 'status_end' value) : This simple SQL query works : select a.app_name from event e, application a where a.id = e.app_id and e.status_end is null; I wrote this django code : apps_querysset = Application.objects.filter(event__status_end__isnull=True) However, this code gererates a LEFT OUTER JOIN, so there are lot's of 'application' objects returned. SELECT "appstat_application"."id", "appstat_application"."app_name", "appstat_application"."app_pub_date", "appstat_application"."app_type_id", "appstat_application"."app_site_id" FROM "appstat_application" LEFT OUTER JOIN "appstat_event" ON ("appstat_application"."id" = "appstat_event"."app_id") WHERE "appstat_event"."status_end" IS NULL Do you have any idea? -
Making queries from existing tables (postgresql) in Django?
I have already created a set of tables with Postgresql, I would like, to make a query directly from tables to Django views without writing any models to pose as a form? -
Django db raw MySQL execute
I have a model and custom manager model class VideoDescription(models.Model): title_eng = models.CharField(max_length=120, unique=True) title_ru = models.CharField(max_length=120, unique=True) slug = models.SlugField(max_length=200, unique=True, blank=True) rating = models.IntegerField(default=0) pub_date_start = models.DateField() poster = models.ImageField(upload_to=get_poster_path) genre = models.CharField(validators=[validate_comma_separated_integer_list], max_length=10, default=0) description = models.TextField(blank=True) objects = VideoDescriptionManager() class VideoDescriptionManager(models.Manager): def get_video_by_genre(self, genre): from django.db import connection with connection.cursor() as cursor: cursor.execute('''select m.id, m.title_eng, m.title_ru, m.slug, m.rating, m.pub_date_start, m.poster, m.genre, m.description, COUNT(*) from main_app_videodescription m where genre like "%%%s%%";''', [genre]) result_list = [] for row in cursor.fetchall(): p = self.model(id=row[0], title_eng=row[1], title_ru=row[2], slug=row[3], rating=row[4], pub_date_start=row[5], poster=row[6], genre=row[7], description=row[8]) p.num_responses = row[9] result_list.append(p) return result_list And i've got a error: django.db.utils.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied. Google talking me change [genre] to (genre,) in a raw sql query but it doesn't help. What can i do to fix it? -
Django KeyError on Custom Form Field with allauth and crispy-forms
So for some reason I am getting a KeyError when I try to render an HTML page with django-allauth and django-crispy-forms. I want app_url to be passed as a form field into the page, but can't seem to do so without getting this error. Any ideas? forms.py class MyLoginForm(LoginForm): """ This form only used for django-allauth package (called in Settings.py) """ login = forms.CharField(error_messages=hide_required_text, widget=forms.TextInput(attrs={'placeholder': 'Email'})) # TODO: hide_required_text not working password = forms.CharField(error_messages=hide_required_text, widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) app_url = forms.CharField(widget=forms.HiddenInput(), initial=reverse_lazy('ms_app:index')) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['login'].label = '' self.fields['password'].label = '' self.fields['app_url'].label = '' self.helper = FormHelper() self.helper.layout = Layout( Div('login', css_class='col-md-12'), Div('password', css_class='col-md-12'), Div('app_url', css_class='col-md-12'), HTML('<div class="col-md-12"><br></div>'), FormActions( Submit('submit', 'SIGN IN', css_class='btn btn-signup btn-block', style='padding:15px;font-size:1.25em;font-weight:bold;'), ) ) index.html <form method="POST" action="{% url 'account_signup' %}"> {% crispy signup_form %} </form> KeyError at /ms/ 'app_url' -
How to add object to a one to many relationship in django?
I am building a django web app which requires a one to many model relationship. I read the docs and it says to use a ForeignKey in the model field. In my case every user needs to have a one to many field with the job model which will keep track of completed jobs by that user. Which in django I believe is represented like so: class User(AbstractBaseUser, PermissionsMixin): ... job_history = models.ForeignKey(Job, on_delete=models.CASCADE) The job model looks like this: class Job(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="jobs") created_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=30) description = models.TextField() pay = models.FloatField() category = models.CharField(max_length=3, choices=JOB_CATEGORY_CHOICES) def __str__(self): return self.title def get_absolute_url(self): return reverse('jobs:detail', kwargs={ 'job_pk': self.id } ) In my view I want to add a job to the job_history one to many field. I do not know how to write this however. This is my view so far: @login_required def job_hire(request, account_pk, job_pk): user = get_object_or_404(account_pk) job = get_object_or_404(job_pk) # I now need to save the job object in the one to many field of the user object. But how? messages.success(request, "You have hired an applicant.") return HttpResponseRedirect(reverse('jobs:find')) How do I add the job to the one to many field in the … -
Serving different django templates based on site
When running a django project in multiple places (separate databases, host, etc) is there an extendible solution for providing site-based templates? As an example, I have a view that renders an invoice- part of this is generic across all the sites, but certain sections need to be custom (logo, promotions etc) to each site. One solution is to have separate template folders for each site, that contain these custom templates and then create a custom loader (that goes before the filesystem loader in settings) something like: class SiteLoader(Loader): is_usable = True def get_template_sources(self, template_name, **kwargs): """""" site = Site.objects.get_current() # Get current site based on SITE_ID site_template_dir = os.path.join( settings.BASE_DIR, 'templates', 'sites', site.domain, ) try: yield safe_join(site_template_dir, template_name) except UnicodeDecodeError: # The template dir name was a bytestring that wasn't valid UTF-8. raise except ValueError: # The joined path was located outside of this particular # template_dir (it might be inside another one, so this isn't # fatal). pass This doesn't feel very robust.. It might be ok when there's only a couple of templates but pretty soon it could get unmanageable. (a little annoying to test and debug as well due to relying on the sites framework). Is there … -
Optimizing Django ORM queries
I'm using the handy Django sessions library in my Django project. This allows me to process Session objects via ORM queries. The attributes I can access for each Session object are: Column | Type | Modifiers ---------------+--------------------------+----------- session_key | character varying(40) | not null session_data | text | not null expire_date | timestamp with time zone | not null user_id | integer | user_agent | character varying(200) | not null last_activity | timestamp with time zone | not null ip | inet | not null Where user_id is from the Django User model. Using the Session library, I need to find the number of users in my app who currently don't have an entry in the Session table (and their corresponding IDs). I tried it via the following: logged_in_users = set(Session.objects.values_list('user_id',flat=True)) logged_in_users = [user_pk for user_pk in logged_in_users if user_pk is not None] logged_out_users = set(User.objects.exclude(id__in=logged_users).values_list('id',flat=True)) num_logged_out = len(logged_out_users) #passed to template to display My Session table contains 1.7M rows, whereas the User table contains 408K rows. The code above take an abnormally large amount of processing time (i.e. several minutes), and ultimately gives me a 500 error. Before trouble shooting what went wrong, I feel I also ought to … -
Django generic views problems with url
I'm creating a website which has two list views and a details view. I have no problem getting from the first listview to the second, but I'm unsure of how to make the url for the details view from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', views.ItemsView.as_view(), name='items'), url(r'^(?P<category_id>[0-9]+)/(?P<products_id>[0-9]+)/$', views.DetailView.as_view(), name='details'), ] im not sure what to replace "category_id" and "products_id" with on the bottom url views: from django.http import Http404 from django.shortcuts import render from django.views import generic from .models import Category, Products class IndexView(generic.ListView): template_name = 'products/index.html' context_object_name = 'all_categories' def get_queryset(self): return Category.objects.all() class ItemsView(generic.ListView): template_name = 'products/items.html' context_object_name = 'all_items' def get_queryset(self): return Products.objects.all() class DetailView(generic.DetailView): model = Products template_name = 'products/details.html' html: {% extends 'products/base.html' %} {%block title%}Home{%endblock%} {% block body %} {% if all_items %} <ul> {% for product in all_items %} <li><a href="{?????????}">{{product.name}}</a> </li> {% endfor %} </ul> {% else %} <h3>You have no categories</h3> {% endif %} {% endblock %} also what would go in the url here where the question marks are thanks -
error: command 'gcc' failed with exit status 1 on centos 6.5
When i try to install pyodbc on centos6.5 for python3.4 and django1.8 i have this error: Someone can help me to fix this error. Thanks. -
Python, Django, pickle resource Errno2 No such file or directory:
I'm currently trying to install a poetry generator on my virtualmachine - running ubunutu. When I run the server, and enter the text, and hit generate, I get the below error: Exception Type: IOError Exception Value: [Errno 2] No such file or directory: 'poetry_generator/resources/bigram.pickle' Exception Location: /home/lee/Downloads/PoEmo-master/poetry_generator/architecture/experts/generating_experts/collocation_expert.py in train, line 31 There is no /resources folder within the poetry_generator, and no bigram.pickles file within it either. It identifies linke 31 of the follow script as the issue: (Not sure why everything below isn't being registered as code - but it is) import nltk import os import pickle from pattern import en from poetry_generator.structures.word import Word from poetry_generator.architecture.experts.generating_experts.word_generating_expert import WordGeneratingExpert from poetry_generator.settings import resources_dir class CollocationExpert(WordGeneratingExpert): """Generating most common contexts for words for words""" def __init__(self, blackboard): super( CollocationExpert, self).__init__( blackboard, "Collocation Expert") self.word_tag_pairs = [] def train(self): bigram_pickle_file = os.path.join(resources_dir, 'bigram.pickle') try: with open(bigram_pickle_file,'rb') as f: self.word_tag_pairs = pickle.load(f) except IOError: tagged_words = nltk.corpus.brown.tagged_words(tagset='universal') self.word_tag_pairs = list(nltk.bigrams(tagged_words)) with open(bigram_pickle_file,'w') as f: pickle.dump(self.word_tag_pairs,f) '''Finding verbs for noun ''' def _find_verbs(self, word): word_bigrams = [(a[0], b[0]) for a, b in self.word_tag_pairs if a[0] == word.name and a[1] == 'NOUN' and b[1] == 'VERB' and en.conjugate(b[0], "inf") not in ('be', 'have')] return self.__get_best_collocations(word, … -
django download generated file
Download a generated file (.xlsx). This is a snippet from a view. Are better solutions than this? inventory_file = open(file_path, "rb") response = HttpResponse(inventory_file, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response -
Inline listing shows redundant items in Django Admin
Let me show you an example: admin.py from django.contrib import admin from .models import Author, Book class BookInline(admin.TabularInline): model = Book @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death') fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')] inlines = [BookInline] This configuration generates the following layout: The problem is, this author has only written one book(i.e. Book 009), but I got four books listed out(i.e. Book 009 and three "empty" books). Why is it? How can I disable this feature(or bug, whatever)? -
Django Query Result Structure
I'm fairly new to Django and have been trying to get it to structure a query result in a certain way. After a few hours of trying, I'm hoping someone can show me how to improve the desired result. In this simplified example, a word is created, users submit definitions for that word, and vote on each definition (funniest, saddest, wtf, etc.): models.py from django.db import models class Word(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) word = models.CharField() timestamp = models.DateTimeField() class Definition(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) word = models.ForeignKey(Word, on_delete=models.CASCADE) definition = models.CharField() timestamp = models.DateTimeField() class Vote_category(models.Model): category = models.CharField() class Vote_history(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) definition = models.ForeignKey(Definition, on_delete=models.CASCADE) timestamp = models.DateTimeField() vote = models.ForeignKey(Vote_category, on_delete=models.CASCADE) Expected Query Result Structure word: 'hello', definitions: { { user: 'alice', definition: 'an expression of greeting', votes: { funny: 3, sad: 1, wtf: 7 }, votes_total: 11 }, etc... } Current Query Get the word that was created on a specific date. Then get all its definitions: Word.objects.filter(timestamp__date=datetime.date(2017, 2, 5)).values('definition__definition') Current Result <QuerySet [{'definition__definition': 'an expression of greeting'}, {'definition__definition': 'blah blah blah'}]> Thanks for any help you can provide. -
Django filters and serializers. Filter model one-to-many nested values
I know how to apply filter to viewset for current model by nested values and return all data concerning to this foreign key. And that's okay if I have one-to-one relation. But I have one-to-many relation. So I don't know how to filter also these "many values". Now I have smth like this. filters.py: class VersionFilter(FilterSet): tool = CharFilter(method='tool_filter') def tool_filter(self, queryset, name, value): queryset = queryset.filter(changes__tool=value).distinct() return queryset class Meta: model = Version fields = ('tool') serializers.py: class ChangeSerializer(serializers.ModelSerializer): class Meta: model = Change fields = ('tool', 'date', 'type', 'title', 'description') class VersionSerializer(serializers.ModelSerializer): changes = ChangeSerializer(many=True, read_only=True) class Meta: model = Version fields = ('date', 'version', 'changes') viewsets.py: class VersionViewSet(ReadOnlyModelViewSet): model = Version queryset = Version.objects.all() serializer_class = VersionSerializer filter_class = VersionFilter And here is the return for url smth like 127.0.0.0/api/version?tool=General: "data": [ { "date": "2017-03-21T10:25:47.848959Z", "version": "1.12", "changes": [ { "tool": "General", "date": "2017-03-21T10:26:22.838785Z", "type": "Fix", "title": "dfa", "description": "" }, { "tool": "General", "date": "2017-03-21T10:26:08.379112Z", "type": "Fix", "title": "dasf", "description": "" } ] }, { "date": "2017-03-21T10:33:43Z", "version": "1.01.12", "changes": [ { "tool": "General", "date": "2017-03-21T10:44:35.143232Z", "type": "Improvement", "title": "qw", "description": "" }, { "tool": "Costs", "date": "2017-03-21T10:34:12.482258Z", "type": "Fix", "title": "dfaasss", "description": "" } ] … -
Query two models in Class Based View
I am attempting to run more than two queries within my IndexView, and display the results within my template. However, I can't seem to add to my get_queryset or get_context_data without getting a whole bunch of errors... How would I go about pulling data from two different models into one view? Thanks in advance for your help! views.py class IndexView(generic.ListView): template_name = 'argent/index.html' context_object_name = 'object_list' def get_queryset(self): return Entry.objects.all() def get_context_data(self, **kwargs): et = super(IndexView, self).get_context_data(**kwargs) et['filter'] = Entry.objects.filter(date=today_date) return et models.py class Entry(models.Model): date = models.DateField(blank=True, null=True,) euros = models.CharField(max_length=500, blank=True, null=True) comments = models.CharField(max_length=900, blank=True, null=True) euros_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) xrate = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) dollars_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) daily_savings_dollars = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) daily_savings = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) def get_absolute_url(self): return reverse('argent:detail', kwargs={'pk': self.pk}) def item_date(self): row_title = self.date return row_title class Savings(models.Model): total_spent_euros = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) total_spent_dollars = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) total_savings = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) def get_absolute_url(self): return reverse('argent:detail', kwargs={'pk': self.pk}) -
The previous dev quit without commenting/documenting the code, he's now MIA; and I've been dropped into his project to drag it across the finish line
It's a django project that uses mongo as a back end for the data that is entered by the users. There is a PSQL db that stores user info only. There are 3 collections in mongo: classes, people, and sets. Classes are supposed to contain people. Classes have their own attributes, but should also have the mongo equivalent of a foreign-key (people_id) that points to a 'people'. People are a collection of attributes that define a type of person: height, weight, age, sex, etc. Sets are collections of both classes and people. So a Set has its own attributes and contains a collection of classes. Classes have their own attributes and contain a collection of people. People have their own attributes. 1) How can I define this in mongo? Pointing me towards a resource is sufficient, but feel free to use foos, bars, and psuedocode. 2) The application is using PyMongo and instantiates MongoClient() at each step of the operation, which seems inefficient. I could use some help here. I'll post updates and answers to questions - I realize this is very vague. Time is short and there is plenty of work left to do. Thanks in advance. -
Caching and crsftoken
A view could be completely cached forever except the crsftoken, which obviously should not be cached. Is it possible to disable caching just for it or how is the common way of implementing this? -
Django rejects certain Slug URLs but accepts others
I have a Django project I am working on, I have just realised that certain URLs are rejected by the server with the error: NoReverseMatch: Reverse for 'mapView' with arguments '(u'intranet.hieta.biz',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'QMSv2/(?P[\w-]+)/$'] The weird thing I dont get about this that half of the pages work and are reachable but the others arent. They all share the same format, database, view, url, template.. I cannot spot a difference. This is the url it is trying to match it to: url(r'^(?P[\w-]+)/$', views.mapView, name="mapView") If anyone has any idea of what might cause Django to reject certain slugs and not others then please let me know any help is immensely appreciated!! Note: All pages are rendered with the same template, url and view. The slugs are all in the same database and the slugs themselves are all generated from the same function. -
How could I communicate asynchronously templates and views in Django?
I'm developing a Django application and in one of the views I have a loop which is controlled by a delay. My purpose is to change dynamically the delay value since my template using a form. I give a pseudocode example below: temaplate.html <body> <form> # Here I want to input a value, and change the x_seconds value in the view. </form> </body> views.py def myview(): items = [...] # A list with some items for item in items: print item delay(x_seconds) # Delay after print the item to see the algorithm behaviour -
Django and mysql on different servers performance
I hvae django app that needs to be extremely fast, and it works good for now. So my question is, is it better to put django app on one server and mysql on another server, or on one server both? I ask because of communication between then. I use digitalocean, and both are on one server.