Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why i get 404 on querying select2 in django admin?
I added select2 to urls.py: url(r'^select2/', include('django_select2.urls')), And make widget in admin: class WordSelect2MultipleWidgetForm(forms.ModelForm): class Meta: model = SeoTextCategory fields = ( 'words', ) widgets = { 'words': ModelSelect2MultipleWidget( model=Word_Replace, search_fields=['word__icontains']), } class SeoTextCategoryAdmin(ModelAdmin): form = WordSelect2MultipleWidgetForm In my admin it looks great, but i get 404 when trying type something: [14/Nov/2016 11:21:47] "GET /select2/fields/auto.json?term=%D0%BF%D1%80&field_id=MTQwNDI5MDk2NTQ5OTYw%3A1c6BaH%3AaaeoV6gvQ0QtjH5FC1q3VDwwFcY HTTP/1.1" 404 932 Am i need to do something in views.py? -
django with rest_framework not finding urls
I am using django with django rest framework. I had an app which I built and I wanted to change around a bit so I started a new project and copied it in. Changed all the files and inports where I knew they needed to be, etc. I got my tests passing again and the testserver is running. as far as I can see, everything is good except the DRF ViewSet I am using. I am getting a 404 when I go to the URL that should be returning a viewset... app.urls.py... router = routers.DefaultRouter() router.register(r'get-data', views.CrimeViewSet) urlpatterns = [ url(r'^$', views.map, name='map'), url(r'^', include(router.urls)), ] app.views.py... def map(request): """The view that will render the map""" return render(request, 'map.html', {}) class CrimeViewSet(viewsets.ReadOnlyModelViewSet): """Viewset for giving crime coordinates""" queryset = Crime.objects.filter(lat__isnull=False).filter(lng__isnull=False) serializer_class = CrimeSerializer filter_class = CrimeFilter now when I go to this url... http://127.0.0.1:8000/phoenix/get-data I get a 404 that says it tried these URLS, which has the URL I tried....and still doesnt work so I have no idea what to do next. Using the URLconf defined in mapofcrime.urls, Django tried these URL patterns, in this order: ^admin/ ^phoenix ^$ [name='map'] ^phoenix ^ ^get-data/$ [name='crime-list'] ^phoenix ^ ^get-data\.(?P<format>[a-z0-9]+)/?$ [name='crime-list'] ^phoenix ^ … -
Django: Return to the same point in last HTML
I'm trying to implement a back button on Django template that once you click on it, you return to the last HTML BUT also to the same point in it (let's say that if you scroll down the page and moved to another one. So when you click back you want to get to the same point and not to the top of the page). Is there any way to do so in Django template without using Ajax? Thanks a lot! -
Manage multiple logins and register accounts in django
i am trying to develop a app which has three account types student login, tutor login ,institute login i have developed three apps named student, tutor and institute but when i am registering a user in student app then by that username i can also login into the tutor app also so how to manage all types of accounts.. forms.py file class UserRegisterForm(forms.ModelForm): #Student_Name= forms.CharField(max_length=300) email = forms.EmailField(label="Email Address") email2 = forms.EmailField(label="Confirm Email") password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(widget=forms.PasswordInput, label="Confirm Password") class Meta: model = User fields = ['username','password','password2','email','email2'] def clean_password2(self): print(self.cleaned_data) password = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') print(password, password2) if password != password2: raise forms.ValidationError("Passwords don't match") else: return password def clean_email2(self): print(self.cleaned_data) email = self.cleaned_data.get('email') email2 = self.cleaned_data.get('email2') print(email, email2) if email != email2: raise forms.ValidationError("Email addresses don't match") email_qs = User.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError("This email has already been registered") else: return email class UserLoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") #user_qs = User.objects.filter(username=username) #if user_qs.count() == 1: # user = user_qs.first() if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("This user does not exist") if not user.check_password(password): raise forms.ValidationError("Incorrect password") if not … -
Logging raw queries Generated by MongoEngine
I need to log all the queries generated by MongoEngine in my Django app. I cannot use cursor._query() as I need to log queries for all the MongoEngine Documents. The logging should be done at app level and not DB level so setting MongoDB profiling level to 2 will not help. I found this gist, which seems helpful but I fail to understand it. Is there a simpler way to write a middleware or any other way I can log all the queries. -
Fabric stream stdout and end in errcode or success code
I'm new to Python and fabric. I'm trying to stream the stdout of a fabric action / task through python to a frontend interface (http call or ws) and end it with a success or reject status. From what I've seen so far, Fabric's in-app API library usage isn't so well made, or I don't understand it. Example: I have this def demo_make_stuff(param1, param2, param2): log = local("cd test/fabrictests/control && ./deploy_stuff.sh " + param1 + " " + param2 if param2 else 0 + " " + param3, capture=True) return log Assigning the actual fabric command to a variable and return it, plus using the capture=True flag will return me the stdout of the bash script, but the stdout will be outputted only when the command finishes. I'd like to get the stdout realtimeand pass through django channels on a frontend websocket stream. Any suggestions? -
Javascripts not working in django inline formset using urlify.js
I am using following models to make a inline formset: class Gallery(models.Model): title = models.CharField(max_length=35) slug = models.SlugField(max_length=35) event = models.ForeignKey(Event, on_delete=models.CASCADE ) class Meta: unique_together = ('slug', 'event') class GalleryForm(ModelForm): class Meta: model= Gallery fields = ('title', 'slug', 'event', 'image') GalleryFormSet = inlineformset_factory(Event, Gallery, extra=0, min_num=1, fields=('title', 'slug', 'image' )) This is worked fine for first formset: <script type="text/javascript"> document.getElementById('id_gallery_set-0-title').onchange = function() { var e = document.getElementById('id_gallery_set-0-slug'); if (!e._changed) { e.value = URLify(document.getElementById('id_gallery_set-0-title').value, 50); } } But when I add more formset above js not work. I inspect html and found next formset title id is:'id_gallery_set-1-title' and slug id is:'id_gallery_set-1-slug' I am using jquery to add formset. My jquery is: $(function() { $('.add-photo').click(function(ev){ ev.preventDefault(); var count = parseInt($('#id_gallery_set-TOTAL_FORMS').attr('value'), 10); var tmplMarkup = $('#gallery-template').html(); var compiledTmpl = tmplMarkup.replace(/__prefix__/g, count) console.log(compiledTmpl); $('div.gallery').append(compiledTmpl); $('#id_gallery_set-TOTAL_FORMS').attr('value', count + 1); }); }); In my javascripts, I also tried title id as 'id_gallery_set-' + count + '-title' but count here is not work. Could anyone suggest me how could I fix my js so that it could work for 'id_gallery_set-1-slug','id_gallery_set-2-slug' and so on. -
Python Django form validation not working
I am trying to do a simple form validation in python django framework,but it doesn't work,whether the form contains the values or not form.is_valid() always returns true forms.py class NameForm(forms.Form): subject = forms.CharField(min_length=5,required=False) message = forms.CharField(widget=forms.Textarea,required=False) sender = forms.EmailField(required=False) cc_myself = forms.BooleanField(required=False) views.py def form_post(request): if request.method=='POST': form = NameForm(request.POST) if form.is_valid(): return HttpResponse('form ok') else: return render(request, 'templates/form.html', {'form': form}) else: form=NameForm() return render(request, 'templates/form.html', {'form': form}) When i submit the form with no value it doesn't show any error message form.is_valid() returns true html <form action="/form/" method="post"> {% csrf_token %} {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.subject.errors }} <label for="{{ form.subject.id_for_label }}">Email subject:</label> {{ form.subject }} </div> <div class="fieldWrapper"> {{ form.message.errors }} <label for="{{ form.message.id_for_label }}">Your message:</label> {{ form.message }} </div> <div class="fieldWrapper"> {{ form.sender.errors }} <label for="{{ form.sender.id_for_label }}">Your email address:</label> {{ form.sender }} </div> <div class="fieldWrapper"> {{ form.cc_myself.errors }} <label for="{{ form.cc_myself.id_for_label }}">CC yourself?</label> {{ form.cc_myself }} </div> <input type="submit" value="submit"> </form> Also one more question How can i use my on html tags instead of django auto-generated form widgets. -
Django ModelForm - How to have search model attributes separately with a modelform?
So I am using the django-autocomplete-light app to add autocomplete dropdown search inputs to my application. My form is made with a model form and I am trying to search my Textbook model. The three different inputs are supposed to be School, Class Name, and ISBN. However, right now I have three fields that all autocomplete with the textbook name. Forms.py class Search(forms.ModelForm): longschool = forms.ModelChoiceField( queryset=Textbook.objects.all().values_list('longschool', flat=True), widget=autocomplete.ModelSelect2(url='textbook-autocomplete') ) class_name = forms.ModelChoiceField( queryset=Textbook.objects.all().values_list('class_name', flat=True), widget=autocomplete.ModelSelect2(url='textbook-autocomplete') ) isbn = forms.ModelChoiceField( queryset=Textbook.objects.all().values_list('isbn', flat=True), widget=autocomplete.ModelSelect2(url='textbook-autocomplete') ) class Meta: model = Textbook fields = ('longschool', 'class_name', 'isbn') widgets = { 'textbook': autocomplete.ModelSelect2(url='country-autocomplete', forward=['longschool', 'class_name', 'isbn']) } HTML <form method="POST" class="index-search-form"> {% csrf_token %} {% for field in form3 %} {{ field }} {% endfor %} <input id="search" class="button" type="submit" value="Search Textbooks" name="Search"></input> </form> So as I said above, when using the application each input autocompletes with the textbook name instead of just the attribute options. So the first field should autocomplete on schools, the 2nd on classes, and the 3rd on isbn. I thought queryset would set what each input autocompletes on but that isn't working. -
logging does not show the result of array
Software Django 1.9 Python 3.4 What did I do? I have the following Django code in my views.py from django.db import connection cursor = connection.cursor() cursor.execute('SELECT p.name, p.name_zh_hans, p.art_number, ....') rows = cursor.fetchall() logger = logging.getLogger(__name__) for row in rows: row_num += 1 logger.info(row) for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) What did I get inside the log file? (0.005) SELECT p.name, p.name_zh_hans, p.art_number, ....; args=None (0.005) SELECT p.name, p.name_zh_hans, p.art_number, ....; args=None (0.006) SELECT p.name, p.name_zh_hans, p.art_number, ....; args=None What did I expect? Display of the array contents inside the log file What went wrong? -
Invalid http_host header
I am trying to develop a website using Django framework and launched using DigitalOcean.com and deployed the necessary files into django-project. I had to include static files into Django-project and After collecting static files, I tried to refresh my ip I am including the tutorials which I have used to create the website. https://www.pythonprogramming.net/django-web-server-publish-tutorial/ I am getting the following error : DisallowedHost at / Invalid HTTP_HOST header: '198.211.99.20'. You may need to add u'198.211.99.20' to ALLOWED_HOSTS. Can somebody help me to fix this ? This is my first website using Django framework. -
Accessing dict values in Django template
I'm having trouble accessing the values of a dict object that I'm trying to send to a template in Django. I can access and print the dict's contents in my view, but when I try to send the data to my template there are all kinds of characters like it isn't encoded properly. At first I thought it might have been an issue with serializing, but I found this post which states that json_serializer.serialize is supposed to be used with a queryset. Is this correct? From here I tried the following. This is in my view function data = {'item_1': 123, 'item_2': 456, 'item_3': ['a','b','c'] } return render(request, 'testsite/new_page.html', {'data' : json.dumps(data.__dict__) } ) In the template I have the following <script>var data = "{{ data }}"; </script> console.log(data); // the following is the improperly formatted result // {&quot;item_1&quot;: 123, &quot;item_2&quot;: 456, &quot;item_3&quot;: [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,] If I don't use json.dumps(data.__dict__) and instead just have json.dumps(data) I get an error about the object is not JSON serializable In my view I have the following. The contents of the dict are properly formatted. print(data.__dict__) import pdb; pdb.set_trace() # displays the dict properly # {'item_1': 123, 'item_2': 456, 'item_3': ['a','b','c'] } In the template … -
Infinite ajax scroll did not working in Django
I am trying to use infinite ajax scroll plugin in my project. I just followed the official website and include the necessary javascript files. Following is my code: <div class="row"> <div class="col-lg-4"> <div class="bootstrap-card"> <img src="{% static 'images/1.jpg' %}" class="img-responsive img-rounded" alt="card imag"> <div class="overlay"> <a class="info" href="#">View Details</a> </div> </div> </div> <div class="col-lg-4"> <div class="bootstrap-card"> <img src="{% static 'images/1.jpg' %}" class="img-responsive img-rounded" alt="card imag"> <div class="overlay"> <a class="info" href="#">View Details</a> </div> </div> </div> <div class="col-lg-4"> <div class="bootstrap-card"> <img src="{% static 'images/1.jpg' %}" class="img-responsive img-rounded" alt="card imag"> <div class="overlay"> <a class="info" href="#">View Details</a> </div> </div> </div> </div> <script src="{% static 'hw1/js/callback.js' %}"></script> <script src="{% static 'hw1/js/jquery-ias.min.js' %}"></script> <div id="pagination"> <a href="page2.html" class="next">next</a> </div> <script> $(document).ready(function() { var ias = jQuery.ias({ container: '.row', item: '.col-lg-4', pagination: '#pagination', next: '.next', delay: 1250 }); }); ias.extension(new IASSpinnerExtension()); ias.extension(new IASTriggerExtension({offset: 2})); ias.extension(new IASNoneLeftExtension({text: "You reached the end"})); </script> So here page2.html is another page in and it does exist. So does anybody know why the error message is: (index):244 Uncaught ReferenceError: ias is not defined(…)(anonymous function) @ (index):244 jquery-3.1.1.min.js:2 jQuery.Deferred exception: jQuery.ias is not a function TypeError: jQuery.ias is not a function at HTMLDocument. (http://localhost:8000/:235:24) at j (http://localhost:8000/static/hw1/js/jquery-3.1.1.min.js:2:29948) at k (http://localhost:8000/static/hw1/js/jquery-3.1.1.min.js:2:30262) undefined -
Django error: no such table "boletin_registrado"
I have this error with a new app I'm developing that is an e-mail bulletin inside my landing page. I made my model (is only one table) named "registrado" inside models.py but when i run server it says that there is no table named "registrado" but... it actually is since I wrote it in models.py and dont know why I'm having this error The code of models.py is this from __future__ import unicode_literals from django.db import models class registrado(models.Model): nombre = models.CharField(max_length = 120, blank = True, null = True) email = models.EmailField() codigo_postal = models.IntegerField() timestamp = models.DateTimeField(auto_now_add = True, auto_now = False) actualizado = models.DateTimeField(auto_now_add = False, auto_now = True) def __unicode__ (self): return self.email Then I modify the settings.py file in INSTALLED APPS putting the name of the app at the end of the list INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'boletin', ] and finally, register the app in admin.py from django.contrib import admin # Register your models here. from .models import registrado class Adminregistrado(admin.ModelAdmin): list_display = ["__unicode__", "nombre", "timestamp"] class Meta: model = registrado admin.site.register(registrado, Adminregistrado) Sorry for the long post and thank you for your help :/ -
Django's Inline Admin: a 'pre-filled' field
I'm working on my first Django project, in which I want a user to be able to create custom forms, in the admin, and add fields to it as he or she needs them. For this, I've added a reusable app to my project, found on github at: https://github.com/stephenmcd/django-forms-builder I'm having trouble, because I want to make it so 1 specific field is 'default' for every form that's ever created, because it will be necessary in every situation (by the way my, it's irrelevant here, but this field corresponds to a point on the map). An important section of code from this django-forms-builder app, showing the use of admin.TabularInline: #admin.py #... class FieldAdmin(admin.TabularInline): model = Field exclude = ('slug', ) class FormAdmin(admin.ModelAdmin): formentry_model = FormEntry fieldentry_model = FieldEntry inlines = (FieldAdmin,) #... So my question is: is there any simple way to add default (already filled fields) for an admin 'TabularInline' in the recent Django versions? If not possible, I would really appreciate a pointer to somewhere I could learn how to go about solving this. Important: I've searched for similar questions here and even googled the issue. I've found some old questions (all from 2014 or way older) that … -
progress bar for upload file(django)
I have the following to upload an image. I am trying to show a progress bar with percentage: <form class="dropzone" id="my-awesome-dropzone" action="{% url "upload" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.non_field_errors }}</p> <div class="fallback"> <p><label>Select zip file only</label></p> </div> <div class="form-group"> <input type="file" class="form-control" name="docfile" multiple> </div> <div class="form-group"> <label for="date">Date Taken :</label> <input class="form-control" type="date" name="date_taken"> </div> <div class="form-group"> <label for="region">Region :</label> <select name="region" class="form-control"> <option value="Semenanjung">Semenanjung</option> <option value="Sabah">Sabah</option> <option value="Sarawak">Sarawak</option> </select> </div> <input type="hidden" name="user_id" value="{{request.user.id}}" /> <center><input type="submit" value="Upload" class="btn btn-primary"/></p></center> </form> please help me do the progress bar -
Cannot get distinct record - Django w / Rest Framework
I define this viewset and i would like to create a custom function that returns distinct of animals species_type called distinct_species. class AnimalViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = Animal.objects.all() serializer_class = AnimalSerializer @list_route() def distinct_species(self, request): query_set = Animal.objects.values('species_type').distinct() serializer = self.get_serializer(query_set, many=True) return Response(serializer.data) This is my Animal model class Animal(models.Model): this_id = models.CharField(max_length=25) name = models.CharField(max_length=25) species_type = models.CharField(max_length=25) breed = models.CharField(max_length=25) .... This is my AnimalSerializer class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = ( 'this_id', 'name', 'species_type', 'breed', ... ) read_only_fields = ('id', 'created_at', 'updated_at') I register the route here. # Create a router and register our viewsets with it. router = DefaultRouter() router.register(r'animal', AnimalViewSet) urlpatterns = [ url(r'^api/', include(router.urls)), url(r'^', IndexView.as_view(), name='index'), ] But when i do this /api/animal/distinct_species/ I got this KeyError: u"Got KeyError when attempting to get a value for field this_id on serializer AnimalSerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the dict instance.\nOriginal exception text was: u'this_id'." -
uwsgi not creating a socket file
I have the following configuration: [uwsgi] vhost = true plugins = python,logfile socket = /tmp/mysite.com.sock master = true enable-threads = true processes = 4 wsgi-file = /home/ubuntu/myappwebsite/myapp/myapp/wsgi.py chdir = /home/ubuntu/myappwebsite/myapp touch-reload = /home/ubuntu/myappwebsite/myapp/myapp/reload logger=file:/tmp/uwsgi-error.log vacuum = true and for nginx: server { listen 80; server_name mysite.com www.mysite.com; access_log /var/log/nginx/mysite.com_access.log; error_log /var/log/nginx/mysite.com_error.log; client_max_body_size 75M; location / { uwsgi_pass unix:///tmp/mysite.com.sock; include uwsgi_params; } } When I look at the nginx logs i see the following: 2016/11/14 01:36:43 [error] 10779#10779: *9 connect() to unix:///tmp/mysite.com.sock failed (111: Connection refused) while connecting to upstream, client: 10.13.142.61, server: mysite.com, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:///tmp/mysite.c I'm not able to find any issues in the uwsgi logs for some strange reason. Is there anything else i'm missing here? I'm using an EC2 with Ubuntu 16.04 if that helps. I have googled and reconfigured this from scratch again and still to no avail. Please, any help appreciated! -
How to run django and wordpress on NGINX server using same domain?
I have tried many ways but do not know how to run Django on example.com and wordpress on example.com/blog The following running project directory structure for Django and Wordpress. Django app dir- /home/ubuntu/django Django app running successfully on - example.com:8000 Wordpress dir - /var/www/html/blog Wordpress running successfully on - example.com Nginx configuration server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /var/www/html/blog; index index.php index.html index.htm; server_name example.com; location / { # try_files $uri $uri/ =404; try_files $uri $uri/ /index.php?q=$uri&$args; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; } } Note- Django app running by gunicorn How to run Django app on example.com and Wordpress on example.com/blog ? -
using for loops for dispaying values in django template
if i use "for loop", all data from Db are presented vertical. I wrote an example without html, for transparency . And second code "my.html" is with html code. I want to be tables showed horizontaly. If i run my.html i got two tables dispayed verticaly, how can I position them horizontaly? {% for post in posts %} {{post.option_one}} {{post.option_two}} {% endfor %} my.html <!-- myprices --> <div id="pricing" class="container-fluid"> <div class="text-center"> <h2>Pricing</h2> <h4>blabla</h4> </div> {% for post in posts %} <div class="row slideanim-'inline'"> <div class="col-sm-4 col-xs-12"> <div class="panel panel-default text-center"> <div class="panel-heading"> <h1><a href="">{{ post.offer_option}}</a></h1> </div> <div class="panel-body"> <p><strong>20</strong> {{post.prop_one}}</p> <p><strong>20</strong>{{post.prop_two}} </p> <p><strong>20</strong>{{post.prop_three}}</p> </div> <div class="panel-footer"> <h3>{{ post.price}}</h3> <h4>{{ post.period}}</h4> </div> <button class="btn btn-lg">Sign Up</button> </div> </div> </div> {% endfor %} -
Django only translating one word
I am attempting a navbar translation to simplified Chinese in Django, however, only the first word is being translated. To wit, I have created a navbar.html with the following content: {% load i18n %} <li><a href="{% url 'homepage' %}">{% trans 'Home' %}</a></li> <li><a href="{% url 'security' %}">{% trans 'Security' %}</a></li> I then do a ./manage.py makemessages -l zh_CN and constructed a file django.po which contains #: templates/navbar.html:20 msgid "Home" msgstr "首页" #: templates/navbar.html:25 msgid "Security" msgstr "安全性" I then did a ./manage.py compilemessages to get the django.mo, which appears to have all the translations I need. As opposed to this question, my LOCALE_PATHS is indeed a tuple: LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) and my LocaleMiddleware is after SessionMiddleware and before CommonMiddleware, as the documentation specifies: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] Yet nonetheless, only Home is translated; all other template variables are left untranslated. To add a bit more mystery, I translated the navbar to Spanish and all variable were translated properly in the browser. This made me suspect my browser was not using the correct language code, so I ran ./manage.py makemessages -l zh-hans and copied over the translation from the zh_CN directory, but no … -
Django: Internationalization of urls and models
I'm working on a little website that should be in Spanish and English. I've spent hours reading the documentation and well, I'm ok with it. Also, I think I'm gonna be using Django-parler to do the model internationalization but I've never use internationalization with Django let alone django-parser and I have a couple of questions. How does Django-parler works in the django-admin? It says: "Nice admin integration." Does Django-parler chose the right language in the model from the i18n_patterns? I would really love if you'd put together the simplest of example for this. I'm really struggling with this. Thanks in advance. PS. I chose django-parler cause of a recommendation in freenode #django. I'm not married to django-parler. What I want is to internationalize the templates (django provides that) and to be able to internationalize the model content from django admin. -
urls parameter dont work
my parameter didn't work for task_fn2. here are my urls url(r'^delete/(?P<task_id>[0-9]+)/(?P<task_fn>[^/]*)/(?P<task_fn2>[^/]*)$', views.base_delete, name='base_delete'), views def base_delete(request, task_id, task_fn=None, task_fn2=None): task = get_object_or_404(Basemap, pk=task_id) task.delete() directory='/var/www/html/tileserver/' os.chdir(directory) os.unlink(task_fn) shutil.rmtree(task_fn2) return redirect('base_browse') html x =window.location='{% url 'base_delete' task.id task.fn task.fn2 %}' and database picture -
django how to group on ManyToMany relationship dynamically
I have what I believe is a simple request but I have been beating my head against a wall and I am not getting any smarter for it. I am using django 1.10. What I am trying to do is get a list of my members grouped by my family field The models look like this: class Family(models.Model): family_name = models.CharField(max_length=200) class Member(models.Model): name = models.OneToOneField(User) family = models.ManyToManyField(Family,blank=True,related_name='members') So i can set my view to use members = Member.objects.order_by('family') or members = Family.objects.order_by('family_name') This obviously holds my members or my families but not both. How would i get this to have both the member name and their family and then group by it? Any help would be appreciated. -
how to django debugging tool setup properly?
I am really new with python, django-oscar. I am trying to set up a debugging tool in pycharm I went through the documentation at http://django-debug-toolbar.readthedocs.io/en/stable/installation.html#internal-ips I have a few questions which I tried Google but pretty much all gives me the documentation links. I am using ubuntu with python 2.7.6, django-oscar 1.2.1, django 1.9 I followed the documentation up to the last step of the installtion "INTERNAL_IPS" but I have no idea where to add that. Is there a specific file to should create or find in order to do add the ip? Also, after all steps are done, how to I use the debug toolbar? In the documentation, there's something about JQUERY_URL and lots other stuffs which I am pretty much lost in here. Can someone please point me to the right direction? Thanks in advance