Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to insert records to a Postgres database(table) using Python object oriented programming
I have this table (made in Django) class Prefixe(models.Model): remote_as = models.CharField(max_length=250) prefix_list = models.CharField(max_length=250, null=True) def __init__(self, remote_as, prefix_list): self.remot_as = remote_as self.prefix_list = prefix_list how can I add some some records to this table: def insert(): p = Prefixe('Apress', 'Berkeley') p.save() -
Unable to access Askbot homepage on port 8080 after installation on CentOS 7
I have installed Askbot on my CentOS 7 VM using steps available online. For instance, https://www.howtoforge.com/tutorial/how-to-install-and-configure-askbot-with-nginx-on-centos-7/ After askbot-setup, when running final manage.py commands, python manage.py syncdb python manage.py runserver 0.0.0.0:8080 I see following warnings: (test) [askbot@testserver qanda]$ python manage.py syncdb WARNING!!! You are using a 'locmem' (local memory) caching backend, which is OK for a low volume site running on a single-process server. For a multi-process configuration it is neccessary to have a production cache system, such as redis or memcached. With local memory caching and multi-process setup you might intermittently see outdated content on your site. System check identified some issues: WARNINGS: django_authopenid.UserPasswordQueue.user: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField. HINT: ForeignKey(unique=True) is usually better served by a OneToOneField. group_messaging.SenderList.recipient: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField. HINT: ForeignKey(unique=True) is usually better served by a OneToOneField. Operations " runserver output: (test) [askbot@testserver qanda]$ python manage.py runserver 0.0.0.0:8080 WARNING!!! You are using a 'locmem' (local memory) caching backend, which is OK for a low volume site running on a single-process server. For a multi-process configuration it is neccessary to have a production cache system, such as … -
Using django ORM from non django python script
Here is the scenario. I have Django project and python script project under a directory. The python script needs to runs independently on a scheduled time and also needs to access Database used by Django. Is it possible to use/import existing Django code in python script to access db. If so how? The idea comes for C# app where Models and data access layer can be built as library and can be used in many projects. -
Proper way to change language on website?
I'm doing a website and would like to include language change. What is the proper way to handle this ? Just copy html's, rename and translate them and change links ? Or is there a better way ? I'm using django. -
Django 1.11 dict as input to .create?
Django 1.11 I have working code something = MyModel.objects.create( a=1,b=2 ) where a and b are the fields. I would like to change it to: mydict = {'a' : 1, 'b' : 2} something = MyModel.objects.create(mydict) I tried something = MyModel.objects.create(**mydict) and something = MyModel(**mydict) Both give this error: Exception Value: 'str' object has no attribute '__name__' I realise I can write some code to do it item by item, just curious if there is a direct way to do that, seems to be something useful.. Thanks! -
How to deploy Django/React/Webpack app on Digital Ocean through Passenger/Nginx
I'm trying to deploy a web app built with Django/Redux/React/Webpack on a Digital Ocean droplet. I'm using Phusion Passenger and Nginx on the deployment server. I used create-react-app to build a Django app which has a frontend that uses React/Redux, and a backend api that uses django-rest-framework. I built the frontend using npm run build. The Django app is configured to look in the frontend/build folder for its files and everything works as expected, including authentication. It's based on this tutorial: http://v1k45.com/blog/modern-django-part-1-setting-up-django-and-react/ On my development machine, I activate a Python 3.6 virtual environment and run ./manage.py runserver, and the app is displayed at localhost:3000. On the deployment server, I've cloned the files into a folder in var/www/ and built the frontend. I've set up Passenger according to the docs with a file passenger_wsgi.py: import myapp.wsgi application = myapp.wsgi.application And the wsgi.py file is in the djangoapp folder below: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') application = get_wsgi_application() I think this is working correctly because Passenger and Nginx are running without error and the app's index.html page is being served up at the server's IP address. However, none of the app's content is being filled in. The web page … -
Django Postgres ArrayField makemigrations
I'm looking to use the PostgreSQL-specific ArrayField in my Django project, but it doesn't show up in the migrations after I run makemigrations. Any ideas why? Django v2.1 Postgresql v9.6.6 # Models.py from django.db import models from django.contrib.postgres.fields import ArrayField class MyClassName(models.Model): udi = ArrayField(models.CharField()), version = models.IntegerField() Then I run: python3 manage.py makemigrations # 0001_initial.py migrations.CreateModel( name='MyClassName', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('version', models.IntegerField()), ], ), As you can see, the field 'udi' is suspiciously missing. -
Django 1.11.17 TypeError: 'context must be a dict rather than Context', except IT IS A DICT
I have recently switched from Django 1.9 to 1.11.17 and one thing is bothering me a lot. There is this error that says TypeError at /somepath context must be a dict rather than Context The line that is throwing it is: return render(request=request, template_name="mytemplate.html", context={"form": form, "update": updateType}) There are many answers on SO where people use RequestContext or Context instead of dict for context and switching to dict solves their problem. But not for me. Here I am pretty sure that my context is in fact a dict. What is interesting if I change it to: return render(request=request, template_name="mytemplate.html", context={}) The error goes away, but obviously causes another error later on. Do you guys have any idead on what am I doing wrong here? -
Django : m2m relationship create two line instead of one
I have extended the UserModel this way : # users/models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): # add additional fields in here credit = models.IntegerField(default=200) follow = models.ManyToManyField('self', related_name='follow') def __str__(self): return self.username But I am stuck as to how I should add/remove a follower. I have created a view with : @login_required def follow(request, user_id): user = get_object_or_404(CustomUser, pk=user_id) if CustomUser.objects.filter(follow=user.pk).exists(): request.user.follow.remove(user) else: request.user.follow.add(user) return redirect('profil', user_id) Let's say request.user.pk is 1 and user_id is 2. For the add part (in the else), I would expect a new line in database with from_customuser_id=1 and to_customuser_id=2 however, it creates two lines: one with from_customuser_id=1 and from_customuser_id=2 as expected one with from_customuser_id=2 and from_customuser_id=1 which I don't need. And for the remove part (in the if), I would expect it to only remove the line from_customuser_id=1 and from_customuser_id=2 But it removes the two lines. I read the doc about django models relations but didn't found how to solve this issue. Not sure if it is relevant but for sake of completeness this is the related part of my urls.py : path('follow/<int:user_id>', views.follow, name='follow'), path('unfollow/<int:user_id>', views.follow, name='unfollow'), And this is how I call them in templates : {% … -
How do I make Django Form Fields Disappear with Javascript?
I have a form in my Django application. What I'm attempting to do is create a form that is filled out in parts. I'm trying to allow the user to navigate the form by clicked on "next" and "prev" buttons to hide and show different steps of the field. The following is my HTML: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!--Meta data and stylesheet linking--> </head> <body onload="loadFunction()"> <header> <!--Header--> </header> <section id="form-section"> <div id="form-container"> <form class="form" method="post"> {% csrf_token %} <div id="1"> <h2>Step 1 of 3</h2> <div class="form-group"> <label for="info_field" class="sr-only">Info Field</label> {{ form.info_field }} </div> <!--There are a few more fields like this --> <div class="form-group"> <a onclick="stepChange(1, next)" href="#">Next</a> <a onclick="stepChange(1, last)" href="#">Last</a> </div> </div> <div id="2"> <h2>Step 2 of 3</h2> <!--Several form fields--> <div class="form-group"> <a onclick="stepChange(2, prev)" href="#">Previous</a> <a onclick="stepChange(2, next)" href="#">Next</a> </div> </div> <div id="3"> <h2>Step 3 of 3</h2> <!--Several form fields--> <button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button> <div class="form-group"> <a onclick="stepChange(3, first)" href="#">First</a> <a onclick="stepChange(3, prev)" href="#">Previous</a> </div> </div> </form> </div> </section> <footer id="mainFooter"> <p>Footer Info.</p> </footer> <script> function stepChange(var step, var cmd) { if(cmd == first) { var x = document.getElementById("3"); var y = document.getElementById("1"); x.style.display = "none"; y.style.display … -
Running uWSGI and Django in Docker on Arch Linux. uWSGI fails every time I use the requests module
I'm running a Django app with uWSGI in Docker with docker-compose. I get the same error every time I: Send a POST request with AJAX In handling said request in my view, I use python's requests module, i.e. r = requests.get(some_url) uWSGI says the following: !!! uWSGI process 13 got Segmentation Fault !!! DAMN ! worker 1 (pid: 13) died :( trying respawn ... Respawned uWSGI worker 1 (new pid: 24) spawned 4 offload threads for uWSGI worker 1 The console in the browser says net::ERR_EMPTY_RESPONSE I've tried using the requests module in different places, and wherever I put it I get the same Segmentation Fault error. I'm also able to run everything fine outside of docker with no errors, so I've narrowed it down to: docker + requests module = errror. Is there something that could be blocking the requests sent with the requests module from within the docker container? Thanks in advance for your help. Here's my uwsgi.ini file: [uwsgi] chdir = %d module = my_project.wsgi:application master = true processes = 2 http = 0.0.0.0:8000 vacuum = true pidfile = /tmp/my_project.pid daemonize = %d/my_project.log check-static = %d static-expires = /* 7776000 offload-threads = %k uid = 1000 gid … -
How to send email after updating a user?
I want when updating a user, he / she receives an email informing that an update has occurred in the user, I tried something like: @transaction.atomic def update_student(request): try: student = request.user.student except Student.DoesNotExist: student = Student(user=request.user) if request.method == 'POST': form = StudentUpdateForm(request.POST, instance=student) if form.is_valid(): form.save subject = 'Usuario atualizado' from_email = settings.EMAIL_HOST_USER to_email = [student.email] update_message = 'Usuario ativado com sucesso' send_mail(subject,from_email=from_email,recipient_list=to_email,message=update_message,fail_silently=False) return redirect('student_list') else: form = StudentUpdateForm(instance=student) return render('student_list') But without success :( Any suggestion? -
Editing pickled BinaryField in Django admin
I have a Parameter model to store parameter types (about 20-30 possible parameter_types) and their corresponding values. Example values that I want to save in this table are: ╔═════════════════╦═══════════════════════╗ ║ parameter_type ║ value ║ ╠═════════════════╬═══════════════════════╣ ║ "min" ║ 12 ║ ╠═════════════════╬═══════════════════════╣ ║ "initial_value" ║ -2 ║ ╠═════════════════╬═══════════════════════╣ ║ "prior_dist" ║ "normal" ║ ╠═════════════════╬═══════════════════════╣ ║ "prior_par" ║ {"mu": 0, "sd": 1} ║ ╠═════════════════╬═══════════════════════╣ ║ "start_values" ║ [-2, 0, 2] ║ ╠═════════════════╬═══════════════════════╣ ║ "initial_dist" ║ "uniform" ║ ╠═════════════════╬═══════════════════════╣ ║ "initial_par" ║ {"min": -3, "max": 3} ║ ╚═════════════════╩═══════════════════════╝ To perform this, I followed the advise from HERE and used pickle. import pickle from django.db import models class Parameter(models.Model): model = models.ForeignKey(MyModelClass, on_delete=models.CASCADE, related_name='parameters') parameter_type = models.CharField(max_length=30) _value = models.BinaryField() def set_data(self, data): self._value = pickle.dumps(data) def get_data(self): return pickle.loads(self._value) value = property(get_data, set_data) class MyModelClass(models.Model): method = models.CharField(max_length=30) This allowed me to store data as I intended. but I cannot use django.admin (possibly since BinaryField '...can’t be included in a ModelForm'). Now, I can only add values using Django's shell. Is there a way to customize admin to enable entering data to this value field? I don't want to change the data structure significantly. But given the limited number of parameter_type options, and … -
Problem connecting existing MSSQL server database to django project.
I need to connect a django project to an excisting MS SQL-Server database however I'm getting an error I don't understand: django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][Driver Manager ODBC] Nome origine dati non trovato e driver predefinito non specificato. (0) (SQLDriverConnect)') English translation I found after googling this: django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') I have no idea what this means, however, I found this question which showed how to setup the DATABASES values in django. Currently my DATABASES looks like this: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': '<DATABASE NAME>', 'HOST': '<PCNAME>\SQLEXPRESS', 'USER': '<USERNAME>', 'PASSWORD': '<PASSWORD>', 'PORT': '', 'OPTIONS': { 'driver': 'SQL Native Client', 'dsn': 'dsn_entry', 'host_is_server': True } } } the server is on localhost and I'm using windows 7, django 2.1, python 3.7 and SQL Server 2014 Express What is this error and what am I doing wrong? -
How to eliminate a tuple according to the column value
When a user register a law, the user id (user_id) and the law id (law_id) is saved in marked table. When a user insert a description in a law, a new tuple is created with the same user_id and the same law_id. I'm trying to get the law data only once, but my query is returning a law for each tuple that exists in marked table. My model: class Law(models.Model): name = models.CharField('Nome', max_length=100) description = models.TextField('Descrição', blank = True, null=True) updated_at = models.DateTimeField( 'Updated at', auto_now=True ) class Marked(models.Model): law = models.ForeignKey(Law, on_delete=models.CASCADE, verbose_name='Lei', related_name='marcacaoArtigos') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='markedUser', related_name='markedUser') My query: user1 = User.objects.get(id= request.user.id) marked = user1.markedUser.all() That's my table: "id" "description" "law_id" "user_id" "1" "desc1" "1" "1" "2" "desc2" "1" "1" "3" "desc3" "1" "1" "4" "desc4" "2" "1" "5" "desc5" "2" "1" So in this case, I want to receive law_id=1 once and law_id=2 once. But I'm receiving law_id=1 three times and law_id=2 twice. -
single signin between python cgi and python django
There are one project using Python Django, another stand alone project using python cgi. Both has it own user auth. module. What would be a simple way to merge user management together? I mean signin already built in python cgi, i want to use the same signin for python django, how i can pass authenticated user_id and username from python cgi to python django.currently i am using mysql database for both application usually in django we will passing authenticated user as follows in views.py user = request.user Thanks -
Django - How to do multi level/ daisy-chained model queries?
Background I need to query a data which is spread across multiple tables. My models look like this: class Clients(models.Model): display_name=models.CharField(max_length=70, null=True) CLIENTSTATUS=(('unknown', 'unknown'), ('active', 'active'), ('inactive', 'inactive'), ('prospect', 'prospect'), ('coi', 'center of influence')) client_status=models.CharField(max_length=25, choices=CLIENTSTATUS, default=CLIENTSTATUS[0][0]) class Accounts(models.Model): nickname=models.CharField(max_length=45, null=True) currency=models.CharField(max_length=3, null=True) class Client_Accounts(models.Model): client=models.ForeignKey(Clients, on_delete=models.CASCADE) account=models.ForeignKey(Accounts, on_delete=models.CASCADE) class Positions(models.Model): account=models.ForeignKey(Accounts, on_delete=models.CASCADE) security_name=models.CharField(max_length=30, null=True) cusip=models.CharField(max_length=9, null=True) file_date=models.DateField(null=True) market_price=models.DecimalField(max_digits=12, decimal_places=5, blank=True, null=True) quantity=models.DecimalField(max_digits=13,decimal_places=3,blank=True, null=True) market_value_trade_date=models.DecimalField(max_digits=14,decimal_places=2,blank=True, null=True) class Securities(models.Model): cusip=models.CharField(max_length=9, null=True) short_name=models.CharField(max_length=45, null=True) Task I am trying to pass the client ID from the front end and I intend to capture all the positions held by all the accounts of that client. I can do that using SQL, if I run this query: select cl.id as client_id, cl.display_name, ac.id as account_no, ac.nickname, pos.cusip, sec.short_name, pos.market_price, pos.market_value_trade_date, pos.quantity from datahub_accounts ac join datahub_client_accounts cl_ac on ac.id=cl_ac.account_id join datahub_clients cl on cl_ac.client_id=cl.id join datahub_positions pos on pos.account_id=ac.id join datahub_securities sec on pos.cusip=sec.cusip where cl.id = 15 and pos.file_date="2018-11-12" group by cl.id, cl.display_name, ac.id, pos.cusip, sec.short_name, pos.market_price, pos.market_value_trade_date, pos.quantity Expected Outcome The JSON I am looking at is something like this: { client_id=15, display_name="Client's Name", { account_no=19, account_name="first account" { cusip="cusip number 1" short_name="cusip 1 short name" market_price=17.59 market_value_trade_date=7724.72 quantity=446.00 }, { cusip="cusip number … -
remove Arial and Helvetica from summernote
I just truing to stay only Roboto, but summernote add to this Arial and Helvetica. Can i just delite it? SUMMERNOTE_CONFIG = { 'summernote': { # As an example, using Summernote Air-mode 'airMode': False, # Change editor size 'width': '100%', 'height': '480', 'fontNames': ['Roboto Light', 'Roboto Regular', 'Roboto Bold'], 'fontNamesIgnoreCheck': ['Roboto Light', 'Roboto Regular', 'Roboto Bold'], 'toolbar': [ ['style', ['style']], ['fontname', ['fontname']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['height', ['height']], ['table', ['table']], ['insert', ['link', 'picture', 'hr']], ['view', ['fullscreen', 'codeview']], ['help', ['help']] ], 'styleTags': ['p', 'h1', 'h2', 'h3', 'small'], }, } I am using django-summernote, but I think thats doesnt matter. -
(Django) Only one loop executes in Ajax success function
I am trying to implement a few dynamic 'selects', that change via an Ajax call. The desired result: When choosing a country, Ajax call loads both 'Network' and 'Regions' The HTML form screenshot The current result: Only one select field is populated with the results, even though both arrays are passed successfully. The Code $ django-admin --version 2.1.2 # models.py from django.db import models class CommonInfo(models.Model): timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True class Country(CommonInfo): name = models.CharField(max_length=55) def __str__(self): return self.name.title() class Region(CommonInfo): country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=55) def __str__(self): return self.name.title() class Network(CommonInfo): country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) region = models.ForeignKey(Region, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=55) def __str__(self): return self.name.title() class Channel(CommonInfo): country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) region = models.ForeignKey(Region, on_delete=models.SET_NULL, null=True) network = models.ForeignKey(Network, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=55) def __str__(self): return self.name.title() # forms.py from django import forms from myapp.models import Country, Channel class CreateChannelForm(forms.ModelForm): country = forms.ModelChoiceField(queryset=Country.objects.all()) class Meta: model = Channel fields = [ 'country', 'region', 'network', 'name', ] # urls.py from django.urls import path from myapp.views import ChannelCreateView, pop_select_data app_name = 'myapp' urlpatterns = [ path('channels/add/', ChannelCreateView.as_view(), name='channel-create'), path('ajax/load-regions-networks/', pop_select_data, name='ajax-load-regions-networks') ] # views.py from myapp.models … -
How to open heirarchy children of specific foreignKey in Django?
I am new to Django and trying to make an educational App. I have a Model heirarchy as Subject>Level>Chapter>Topic>Article I want to add Articles on specific Topic in a Specific Chapter of a specific Level in a Subject? How is it possible to open children of specific ForeignKey? E.g. I want this is admin panel, If I click on a subject I get Children Levels and then Children Chapters and so on... models.py from django.db import models class Subject(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Level(models.Model): name = models.CharField(max_length=50) subject = models.ForeignKey(Subject, default=1, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class Chapter(models.Model): name = models.CharField(max_length=50) level = models.ForeignKey(Level, default=1, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class Topic(models.Model): name = models.TextField(max_length=50) chapter = models.ForeignKey(Chapter, default=1, null=True, on_delete=models.CASCADE def __str__(self): return self.name class Article(models.Model): title = models.CharField(max_length=50) body = models.TextField() topic = models.ForeignKey(Topic, default=1, null=True, on_delete=models.CASCADE) def __str__(self): return self.title admin.py from django.contrib import admin from .models import Level, Subject, Article, Chapter, Topic admin.site.register(Level) admin.site.register(Subject) admin.site.register(Article) admin.site.register(Chapter) admin.site.register(Topic) -
relationship error between tables using foreign key
I have the class Pessoa and Veiculo that are related, and I have the class Menssalista, only that I need that when registering someone in the monthly class, selecting Veiculo or Pessoa that automatically only the relaxed data is presented. Example if I choose the Pessoa X that the data of the Veiculo X appear for choice and vice versa. How are you now accepting data that is not related models.py from django.db import models from django.core.mail import send_mail import math, datetime from django.utils import timezone STATE_CHOICES = ( ('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', 'Amapá'), ('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', 'Ceará'), ('DF', 'Distrito Federal'), ('ES', 'Espírito Santo'), ('GO', 'Goiás'), ('MA', 'Maranhão'), ('MT', 'Mato Grosso'), ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'), ('PA', 'Pará'), ('PB', 'Paraíba'), ('PR', 'Paraná'), ('PE', 'Pernambuco'), ('PI', 'Piauí'), ('RJ', 'Rio de Janeiro'), ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'), ('RO', 'Rondônia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'), ('SP', 'São Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins') ) class Pessoa(models.Model): nome = models.CharField(max_length=50, blank=False) email = models.EmailField(blank=False) cpf = models.CharField(max_length=11, unique=True, blank=False) endereco = models.CharField(max_length=50) numero = models.CharField(max_length=10) bairro = models.CharField(max_length=30) telefone = models.CharField(max_length=20, blank=False) cidade = models.CharField(max_length=20) estado = models.CharField(max_length=2, choices=STATE_CHOICES) def __str__(self): return str(self.nome) + … -
Django Rest Framework: can't get user id from given token
I'm dealing with my first Django project. I'm trying to create an api that accepts a token via post request and queries the public_authtoken_token table for the related user id. The dbms I'm using is PostgreSQL 10.6. Django version is 2.1.1 and DRF is 3.8.2 Here's the "view" code I have: from rest_framework.authtoken.models import Token from rest_framework.views import APIView class MyView(APIView): def post(self, request, format=None): my_token = request.META.get('HTTP_AUTHORIZATION') user_id = Token.objects.get(key=my_token).user_id return Response(status=status.HTTP_200_OK) My problem is that I'm getting the following exception when I do user_id = Token.objects.get(key=http_token).user_id : rest_framework.authtoken.models.Token.DoesNotExist: Token matching query does not exist. Now,I have verified that the tokens I used to test it are in the db and they have a valid user_id. Also, I verified that the token I read from the HTTP request is correct as well. Am I doing something wrong? -
Django - Disable form button during calculation
In a webpage the user fill a form and then he obtained an excel file. I'd like to disable the buttons until the download is finished to prevent the user to presses them multiple times. I tried this code: $('form').submit(function (event) { if ($(this).hasClass('submitted')) { event.preventDefault(); } else { $(this).find(':submit').html('<i>Attendi...</i>'); $(this).addClass('submitted'); } }); But the buttons stay disable until I refresh the page. The final chunk of the Django view code is this: response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="%s"' % filename wb.save(response) return response There is some way to re-abilitate the buttons or to force the page to reload after the download is started/finished? -
View thumbnails of uploaded images in django admin
I am trying to add thumbnails to list view in django admin. This is my admin.py for my app, i got this far: from django.contrib import admin from .models import Image from django import forms from django.db import models class ImageAdmin(admin.ModelAdmin): list_display = ("label","tag","order",'Edit','image_img') list_editable= ("order",) list_filter = ('tag',) search_fields = ('tag', 'label') ordering = ['-order'] list_display_links = ('Edit', ) def Edit(self, obj): return "Edit" def image_img(self,obj): if obj.pic: return '<img src="%s" height="100px"/>' % obj.pic.url else: return 'No_image' image_img.short_description = 'Image' image_img.allow_tags = True admin.site.register(Image,ImageAdmin) My object for picture is called "pic". If I simply add it to list view django returns link with full path. I was looking for template for list view so that I can add |safe filter but I couldn't find it. Any other idea how to achieve it? -
Django + PostgreSQL with bi-directional replication
Firstly please let me introduce my use-case: I am working on Django application (GraphQL API using Graphene), which runs in the cloud but also have its local instances in local customer's networks. For example One application in the cloud and 3 instances (local Django app instance with a PostgreSQL server with enabled BDR) on local networks. If there is a network connection we are using bi-directional replication to have fresh data because if there is no connectivity we use local instances. Here is the simplified infrastructure diagram for an illustration. So, if I want to use the BDR I can't do DELETE and UPDATE operations in ORM. I have to generate UUIDs for my entities and every change is just a new record with updated data for the same UUID. Latest record for selected UUID is my valid record. Removal is just a another flag. Till now, everything seems to be fine, problem starts when I want to use for example many-to-many relationship. Relationship relies on the database primary keys and I have to handle removal somehow. Can you please find the best way how to solve this issue? I have few ideas but I do not want to made …