Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display flags in Django form & templates with Django-countries
I'm using Django-countries and I don't overcome to display country flags beside each country in my Django Form or in any templates. I display well the country list, I set correctly the flags folder in my static folder. But impossible to display flags. In my model I have : PaysNaissance = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance') Then, my form displays countries like this : As you can see, none flags appears in my list. Do you have any idea about this issue ? Settings are well-configured, and in my template I have : <tr> <td>Pays de naissance</td> <td> <img src='{{personne.PaysNaissance.flags.url}}'/> </td> </tr> -
Change wagtail admin form fields based on user input
I've got a model called 'Block', which has multiple fields: type. This is a dropdown where you can select 3 options. URL Search Based on the type field, the URL or Search must be shown. The search field needs to preform a search using a variable: API_HOST. I've written JS to do make the form dynamic and I've extended the wagtailadmin/pages/edit.html template to inject the JS. However, I'm not sure how to pass the API_HOST (defined in dev.py) down to the template. How should I approach this situation? -
How to do locale aware sorting in Django?
In Javascript I would use the String.prototype.localeCompare() function: lst = ['Åsheim', 'Aamodt', 'Haagen', 'Hagen'] lst.sort((a, b) => a.localeCompare(b, 'nb', {caseFirst: false, numeric: true})) [ "Hagen", "Haagen", "Aamodt", "Åsheim" ] i.e. sort a and b in the nb (norwegian-bokmål) locale, ignore case (caseFirst: false) and sort numerics by value ('1' < '2' < '10'). Aside: in the nb locale, there are three extra letter at the end: ..xyzæøå and 'aa' is sorted as if it was 'å'. Based on https://docs.python.org/3.0/library/locale.html#background-details-hints-tips-and-caveats I can't use setlocale in Django (since we're running a multithreaded Apache instance). We're developing on windows so a solution using e.g. ctypes to get at glibc won't work for us. I suppose I could convert the list to json, and pass it to nodejs in a subprocess, but there has to be a better way..? -
login_required not working django even after cache clear
I want the user not to navigate back once he is logged out. I used login_required(login_url = "/login/") before my definition of logout view in my views.py. I am still able to navigate back after logging out. How can I ask the user to log in again? Also, If I type URL for my home page (say localhost:8000/home) directly in the browser, I am able to access the page without login. How can I correct this issue? I have cleared browser cache too and still, no use. my views.py: from django.shortcuts import render from django.http import HttpResponseRedirect from django.contrib import auth from django.views.decorators import csrf from django.contrib.auth.decorators import login_required def login(request): c={} # c.update(csrf(request)) return render(request,'login.html',c) def auth_view(request): username = request.POST.get('username','') password = request.POST.get('password','') user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect('/home') @login_required(login_url='/login/') def logout(request): request.session.flush() auth.logout(request) return render(request,'logout.html') -
Can I use the curl in the python project?
In my terminal, I can use curl command, such as: $ curl 'http://www.sohu.com' it will download the source code of the web page. But I want to execute the curl in my python project. Whether is it can be realize? -
Django Path to static files changing depending on the page
I have an index page with a list of mouvements in a datatable, each row has buttons that allow the user to press "Edit" to go to a new page where he can view the details of the mouvement. On index page and on the basic details mouvement page everything work fine, static files are loaded with the path /gestion_mouvements/static/... But when i use "(?P[0-9]+)/$" in my page url to be able to get the mouvement ID in the url, the loaded page change static path to gestion_mouvements/mouvementDetails/static/... for example and fail to load the static files since the path should be gestion_mouvements/static/... I checked and tried many different static settings in settings.py but nothing worked so far, anyone has an idea on how i can change that ? -
Can not migrate schema django-geoposition
I can makemigrations, but can not migrate the schema. django-geoposition==0.3.0 django==1.11.5 python3.6.2 import environ env = environ.Env() ... DATABASES = { 'default': env.db("DATABASE_URL", default="postgres://postgres:postgres@localhost:5432/soken_web") } DATABASES['default']['ATOMIC_REQUESTS'] = True DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.postgis' GEOPOSITION_GOOGLE_MAPS_API_KEY = '<API_KEY>' GEOPOSITION_MAP_OPTIONS = { 'minZoom': 3, 'maxZoom': 15, } GEOPOSITION_MARKER_OPTIONS = { 'cursor': 'move' } INSTALLED_APPS = [ ... 'geoposition', ] from django.contrib.gis.db import models from geoposition.fields import GeopositionField class House(models.Model): ... location = GeopositionField() Problem: django.db.utils.ProgrammingError: data type character varying has no default operator class for access method "gist" HINT: You must specify an operator class for the index or define a default operator class for the data type. References: Django django-location-field missing API Keys https://github.com/caioariede/django-location-field -
how to pass the parameter to a form during formset creation
I have an inline formset in Django. And I wonder how can I set some max_value for a form that is in this formset based on the instance parameters. The problem is that when we create a formset by using inlineformset_factory we pass there not an instance of the form, but the class, so I do not know how to pass the parameters there. when the form is initiated, there is already an instance object available in kwargs that are passed there. But for some strange reasons, when I try to set max_value nothing happens. Right now I've found quite an ugly solution to set the widget max attribute. This one works but I wonder if there is a correct way of doing it. from .models import SendReceive, Player from django.forms import inlineformset_factory, BaseFormSet, BaseInlineFormSet class SRForm(forms.ModelForm): amount_sent = forms.IntegerField(label='How much to sent?', required=True, widget=forms.NumberInput(attrs={'min': 0, 'max': 20}) ) def __init__(self, *args, **kwargs): super(SRForm, self).__init__(*args, **kwargs) curmax = kwargs['instance'].sender.participant.vars['herd_size'] self.fields['amount_sent'].widget.attrs['max'] = int(curmax) class Meta: model = SendReceive fields = ['amount_sent'] SRFormSet = inlineformset_factory(Player, SendReceive, fk_name='sender', can_delete=False, extra=0, form=SRForm,) formset = SRFormSet(self.request.POST, instance=self.player) -
Is there a programmatically way to force a crawler to not index specific images?
I want to stop crawlers from indexing specific images on my website, but only if they're older than a specific date. However, the crawler shall not stop indexing the page where the image is currently linked. My initial approach was to write a script which adds the URL of the image to 'robots.txt', but I think the file will become huge, as we talk about a really huge amount of potential images. My next idea was to use the <meta name="robots" content="noimageindex"> tag, but I think this approach can be error prone, as I could forget to add this tag to a template where I might want to stop crawlers from indexing the image. It's also redundant and the crawler will ignore all images. My question is: do you know a programmatically way to force a crawler too not index a image, if a condition (in my case the date) is true? Or is my only possibility to stop the crawler from indexing the whole page? -
Final year project
i'm a final year student doing software engineering. now its time for me to submit idea for my final project but i'm unable to get any idea which is good and still easy to implement, as i'm interested in doing solo project. i have almost 4-5 months to complete my project. i would like to do my project using python/django, that's why i'm making a humble request. please help me and give me some ideas for my final project. hoping for a favorable response from u people. thank u in advance. -
jquery datatable server-side pagination not working on django rest api
i am trying to add jquery data table pagination using django rest api(post), but does not work properly.here is my data table code, Note please avoid some code where i have done some additional calculation. $(document).ready(function () { $("#question_form").off('submit').on('submit', function (e) { e.preventDefault(); var dtOption = { "columns": [ {"title": "Transaction Id", "data": "id"}, {"title": "Reference Id", "data": "reference_id"}, {"title": "Transaction Type", "data": "transaction_type"}, {"title": "Transaction Ref ID", "data": "transaction_reference"}, {"title": "Accounting Head", "data": "account"}, {"title": "description", "data": "description"}, {"title": "Amount", "data": "amount"}, {"title": "Balance", "data": "balance"}, {"title": "Date Created", "data": "date_created"} ], "destroy": true, "columnDefs": [ { render: function (data) { return (data == 0) ? "Debit" : "Credit" }, targets: 2 }, { targets: 8, render: function (data, a, b) { console.log(data); return moment(data).format('YYYY-MM-DD hh:mm A'); } } ] }; var table = $('#journal_list').DataTable(dtOption); var form_data = $(this).serialize(); console.log(form_data); $.ajax({ method: 'POST', data: form_data, url: '/pms/api/v1/ledger_detail/', success: function (data) { console.log("Responsed data",data); if(data.data.length > 0){ $(".md-card-toolbar-heading-text").text(data.data[0].account + " Ledger"); }else{ $(".md-card-toolbar-heading-text").text("No Ledger Available"); } data.data.balance = ''; for (var i = 0; i < data.data.length; i++) { if (i == 0) { data.data[i].balance = data.data[0].amount; } else { var curentData = data.data[i]; var prevData = data.data[i-1]; var currTransactionType … -
How to change the sort of a ListView
Well i want 3 views: show the Pictures with highes rank first(best view) show the newest Pictures first(fresh view) show the best pictures of the newsest first.(trending) My HTML and view is working, but my sorting dosn't. Here is what i tryed: class FreshList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ("user", "group") def get_queryset(self): queryset = self.model.objects.order_by('-created_at') #queryset = self.model.objects.order_by('-ranking') for BestList #queryset = self.model.objects.order_by('-created_at','-ranking') for TrendingList return queryset class FreshList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ("user", "group") ordering = ('-created_at') #ordering = ('-ranking') for BestList #ordering = ('-created_at','-ranking') for TrendingList Here is my models.py: class Post(models.Model): created_at = models.DateTimeField(auto_now=True) title = models.CharField(max_length=30,default='Titel') bild = models.ImageField(upload_to='images', default='/static/img/Weramemesicon.png') ranking = models.IntegerField(default = 0) -
Django create from hash throws matching query does not exist
This has caused me to nearly tear my hair out. I have the following model hash for the Journal table db_model_fields = {'abbreviation': 'Olympiads Inform.', 'issn': '18227732', 'journal_type': 'p', 'researcher': <Researcher: x Scopus ID r>, #actual researcher object 'title': 'Olympiads in Informatics'} When I try to save the model to the database with Journal.objects.create(**db_model_fields) I get DoesNotExist: Journal matching query does not exist. Which is ridiculous because the researcher definitely exists. Model code: class Journal(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) researcher = models.ForeignKey(Researcher, on_delete=models.CASCADE) title = models.CharField(max_length=255) journal_type = models.CharField(max_length=40,default=None,blank=True, null=True) abbreviation = models.CharField(max_length=200, default=None, blank=True, null=True) issn = models.CharField(max_length=50, default=None, blank=True, null=True) journal_rank = models.IntegerField(default=None, blank=True, null=True) properties = JSONField(default=dict) def __str__(self): return self.title Does anyone have any idea how I can solve this issue? it's being a huge blocker, and nowhere else in stack overflow can I find an answer to this. Thank you! -
Pass form type to view
I want to create a generic view that gets a form type (from forms.py) and render it to html. I need that different urls will pass different forms. lets say I have form1 and form2 classes in forms.py, I need to pass the form to urlpatterns, something like this: urlpatterns = [ url(r'^form_test1/$', views.generic_form, name='form_test', form_type = forms.form1()), url(r'^form_test2/$', views.generic_form, name='form_test2', form_type = forms.form2()), ] Is it can be made? and if not, how can I achieve the required generics. Thanks! -
Partial Update Failed via Viewset Django Rest Framework
I want to update a field in my model whenever an object link is called through the api. I'm using Django Rest Framework to handle the creation of api. The link to a single object is example.com/api/pk/ where pk is the object id. In the model viewset, I wrote a partial update method to handle the addition of 1 to the field whenever the object is called upon. class RocNationViewSet(viewsets.ModelViewSet): queryset=RocNation.objects.filter(is_active=True).order_by('-pub_date') serializer_class=RocNationSerializer filter_backends = (DjangoFilterBackend,) def partial_update(self, request, pk=None): serializer=RocNationSerializer(rocnation, roc_views=F('roc_views')+1, partial=True) serializer.save() return Response(serializer.data) The method is not carrying out the operation. The field in the model is not updated. What am I missing? -
How to extend a list by overwriting the common values
list1=[{"status":1, "s_count":100}, {"status":2, "s_count":20}] list2=[{"status":1, "s_count":0}, {"status":3, "s_count":30}] list1.extend(list2) is giving [{"status":1, "s_count":100}, {"status":2, "s_count":20}, {"status":1, "s_count":0}, {"status":3, "s_count":30}] what I want is, [{"status":1, "s_count":0}, {"status":2, "s_count":20}, {"status":3, "s_count":30}] Thanks in advance. -
How can I makemigrates the other app's Models?
In my project, I use python manage.py makemigrationsand python manage.py migrate to generate the tables. But I find I can not use the two methods to generate the models in other apps? how can I do that? -
How can I check out only specified fields when I query the models?
How can I query the model by constraint some fields, such as I don't want to query out the id, and password. Class AppUser(models.Model): username = models.CharField(max_length=16) password = models.CharField(max_length=64) email = models.CharField(max_length=16) When I query it now the situation is: app_users = models.AppUser.objects.all() # all the fields will be find out. So, how can I check out only specified fields when I query it, I don't want to shows the id and password? -
How delete image files after unit test finished?
In unit test I create 3 objects (articles) at the beginning. After test complete I notice that there are 3 images in media_root folder. Question: How to delete that images which was created after test finished? P.S. I tried to use next code but it delete media_root folder. def tearDown(self): rmtree(settings.MEDIA_ROOT, ignore_errors=True) tests.py: class ArticleTestCase(TestCase): def setUp(self): self.image = open(os.path.join(BASE_DIR, 'static/images/tests/image.jpg'), "r") def test_article_view(self): first_article = Article.objects.create( pk=150, head='First', image=SimpleUploadedFile( name=self.image.name, content=self.image.read(), content_type='image/jpeg' ) ) second_article = Article.objects.create( pk=160, head='Second', image=SimpleUploadedFile( name=self.image.name, content=self.image.read(), content_type='image/jpeg' ) ) third_article = Article.objects.create( pk=170, head='Third', image=SimpleUploadedFile( name=self.image.name, content=self.image.read(), content_type='image/jpeg' ) ) [***] -
Nginx Uwsgi Django 111 Connection refused while connecting to upstream Production deployment
after struggling for almost a week on this I feel I need to reach out for assistance . Please Help I am trying to deploy my project to a production environment In terms of permissions I have read all the forums changed all permissions i.e. 777 etc etc srwxrwxrwx uwsgi.sock (owned by me full access ) I've checked over and over all the directory structures etc Ive swtiched from unix sockets to http but still no joy. exact error > 2017/09/18 06:32:56 [error] 15451#0: *1 connect() to > unix:////home/workspace/project// tmp/uwsgi.sock failed (111: > Connection refused) while connecting to upstream, client: 1933 > .247.239.160, server: website.xyz, request: "GET / HTTP/1.0", > upstream: "uwsgi://unix://// > /home/workspace/project/tmp/uwsgi.sock:", host: "www.website.xyz" Nginx configuration: upstream _django { server unix:////home/workspace/project/tmp/uwsgi.sock;} server { listen 62032; server_name website.xyz www.website.xyz ; location = /favicon.ico { access_log off; log_not_found off; } location = /test-this { return 200 "Yes, this is correct\n"; } location /foo { return 200 "YIKES what a load of codswollop";} root /home/workspace/project; location /static { alias /home/workspace/project/testsite/assets; } location /assets { root /home/workspace/project/testsite/assets; } location / { include /home/workspace/project/uwsgi_params; #include uwsgi parameters. uwsgi_pass _django; #tell nginx to communicate with uwsgi though unix socket /run/uwsgi/sock. } uwsgi ini file … -
django - error adding database to heroku
I am struggling to deploy my app on heroku. Mainly due to database configuration. This is the bottom of the settings.py file, import dj_database_url DATABASES = { 'default': dj_database_url.config() } try: from .local_settings import * except ImportError: pass This is my local_settings.py file, import os BASE_DIR = os.path.dirname(os.path.dirname(file)) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', 'USER': 'test', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': 5432, } } I can run heroku local web successfuly. But when I run , heroku run python manage.py migrate, it gives me error, django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? When I run, heroku run python manage.py shell, And then run >>> import dj_database_url >>> dj_database_url.config() I get the dictionary giving me the full information about the database. Where is the issue ? -
Why isnt my navbar expanding right?
So here is the code for my navbar (i use Django, so the links are dynamic) Well, my navbar doesn't expand to the end(if you use the hamburger), and i don't want to insert a fixed number because it doesn't work. Well, i want the expanded navbar to show login. alternatively i want to keep the login but put it to the other side. body { font: 14px -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica Neue, Arial, Helvetica, Geneva, sans-serif; overflow-x: hidden; overflow-y: auto; } .bild { max-height: 600; } .bild img { min-width: 20%; max-width: 90%; height: auto; position: relative; float: left; background-position: 50% 50%; background-repeat: no-repeat; background-size: cover; } .navbar-brand { padding-top: 40px; } .username a { color: #000000; } .username a:hover { text-decoration: none; color: #6f737a; } a.logo { height: 40px; width: 60px; background: url(../img/Weramemesicon2.png) 50% no-repeat; background-size: 50px 40px; text-indent: -9999px; } .navbar-collapse.in { overflow: hidden; max-height: none !important; height: auto !important; } .top-nav { border-radius: 0px; background: #000000; margin: 0; } .navbar a { text-align: center; font-weight: 700; } .navbar a:hover, navbar a:focus { color: #fff; } .general-function .search { display: inline-block; width: 30px; height: 30px; text-indent: -999px; overflow: hidden; background: url(../img/sprite.png) 0 0 no-repeat; background-size: 420px … -
Send mail with Inline images in Django using django-mail-queue
I want to send inline promotional images in mail content like e-commerce websites sends in their mail. For mailing I have used django-mail-queue package, but I don't know it is supported in it or not. I would appreciate if you help me out. -
How to link existing tables in database to Django Models?
I am learning Django and i need to know whether i can link a table already present in the database to a model (since, i heard that tables are created by Django for whatever models we are creating inside django app ). If so, how can it be done? -
Django: Multiple database for read and write independent of app
How can we work with multiple databases on Django, under some specific conditions such as, 1. One DB for write purpose only ( db_for_write.sqlite3) 2. Two other DB for reading purposes (read_replica_1.sqlite3 ,read_replica_2.sqlite3) 3. All these 3 DB should be synchronized all the time (3 DB should contain same data all the time) 4. All the actions such as CRUD , migration etc are independent of app or model this is my Db_Router.py import random class ExampleDatabaseRouter(object): def db_for_read(self, model, **hints): db_list = ('db_for_read_1', 'db_for_read_2') return random.choice(db_list) def db_for_write(self, model, **hints): return 'db_for_write_only' def allow_relation(self, obj1, obj2, **hints): # I couldn't understand what would do this method return def allow_migrate(self, db, app_label, model_name=None, **hints): # sync all DB return Unfortunately, I couldn't understand the purpose of allow_relation() method. I hope someone could help me.